Lua 语言

精选 Lua 语言 常用指令与核心速查备忘单,涵盖高频用法、配置参数与实用技巧。

#入门指南

#简介 (Introduction)

#Hello World 示例


print("Hello, World!") -- Hello, World!

-- You can omit parentheses if the argument is one string or table literal
print "Hello, World!"  -- Hello, World!

print [[multi-line
 Hello
 World]]


Lua 经典 Hello World 示例

#变量声明 (Variables)


local age = 18 -- local variable
boys, girls = 2, 3 -- global variables

-- Now x = 1, y = 2, z = 3, and 4 is thrown away.
x, y, z = 1, 2, 3, 4

-- Undefined variables return nil.
-- This is not an error:
foo = anUnknownVariable  -- Now foo = nil.

-- Variables are global by default unless declared with local.

Lua is a dynamically typed language and hence only the values will have types not the variables.

#数据类型 (Data Types)

Value Type Description
number Represent (double-precision) numbers
string Represents text
nil Differentiates between values with data or not
boolean true or false value
function Represents a sub routine
userdata Represents arbitrary C data
thread Represents independent threads of execution
table key-value pair, or array.

See: Data Type APIs

#输入输出 (IO)

-- Writes data to the standard output or a file.
io.write("Enter your name: ")
-- Reads input from the user or a file. You can specify formats like "*l" (line), "*n" (number), or "*a" (all).
name = io.read()

io.write("Enter your age: ")
age = io.read()

#代码注释 (Comments)

-- This is a single line comments
--[[
 Comments (multi-line) could also be written like this
--]]

#运算符 (Operators)

#算术运算符 (Arithmetic)

-- add
  result = 10 + 30  -- => 40

-- subtract
result = 40 - 10  -- => 30

-- multiply
result = 50 * 5   -- => 250

-- divide (float division)
result = 16 / 4   -- => 4.0

-- divide (integer division, Lua 5.3+)
result = 16 // 4  -- => 4

-- modulo
result = 25 % 2   -- => 1

-- power
result = 5 ^ 3    -- => 125

-- unary minus
a = 12
result = -a -- => -12

#关系运算符 (Relational)

a = 10
b = 20

-- equals
print(a == b) -- false

-- not equals
print(a ~= b) -- true

-- greater than
print(a > b) -- false

-- less than
print(a < b) -- true

-- greater than or equals
print(a >= b) -- false

-- less than or equals
print(a <= b) -- true

#逻辑运算符 (Logical)

-- and
false and nil  --> false
0 and 20       --> 20
10 and 20      --> 20

-- or
true or false  --> true
10 or 0        --> 10
12 or 4        --> 12

  -- not
not true       --> false

Only nil and false are falsy; 0 and '' are true!

#条件控制 (Conditionals)

#if-else

num = 15
if num > 10 then
  print("num is greater than 10")
elseif num < 10 then
  print("num is smaller than 10")
else
  print("num is 10")
end

-- making a ternary operator
-- This is similar to the a?b:c operator in C/js:
ans = aBoolValue and 'yes' or 'no'  --> 'no'

#Loops

#While loop

i = 1
while i <= 5 do
  print(i)
  i = i + 1
end

#For loop

-- Numeric for loop (start, end, step)
for i = 1, 5, 1 do
  print(i)
end

-- Generic for loop for tables
t = {10, 20, 30}
for k, v in ipairs(t) do
  print(k, v) -- prints 1 10, 2 20, 3 30
end

#Repeat-until loop

i = 1
repeat
  print(i)
  i = i + 1
until i > 5

#Breaking out

while x do
  if condition then
    break
  end
end

#Continue

-- prints even numbers in [|1,10|]
for i=1,10 do
   if i % 2 == 1 then
    goto continue
  end
   print(i)
   ::continue::
end

#Functions

#Creating fns

function myFunction()
  return 1
end

function myFunctionWithArgs(a, b)
  -- ...
end

-- function as arg
function operate(a, b, func)
    return func(a, b)
end



-- anonymous function
function (parameters)
    -- body of the function
end


local greet = function(name)
    return "Hello, " .. name
end


-- Not exported in the module
local function myPrivateFunction()
end


-- Splats
function doAction(action, ...)
  print("Doing '"..action.."' to", ...)
end

#Invoking fns

myFunction()

print(greet("Lua")) -- Output: Hello, Lua


-- function as arg
local result = operate(5, 3, function(x, y)
    return x + y
end)

print(result) -- Output: 8


doAction('write', "Shirley", "Abed")
--> Doing 'write' to Shirley Abed

You can omit parentheses if the argument is one string or table literal

print "Hello World"     -->     print("Hello World")

dofile 'a.lua'          -->     dofile ('a.lua')

print [[a multi-line    -->     print([[a multi-line
 message]]                        message]])

f{x=10, y=20}           -->     f({x=10, y=20})

type{}                  -->     type({})

#Data Type APIs

#Global functions

Assert

local my_table = {}
assert(my_table, "my_table should exist!") -- This will not fail

local a = nil
-- This will cause a runtime error with the message "a is nil"
assert(a, "a is nil")

Type

local my_var = 10
print(type(my_var)) -- "number"

local my_str = "hello"
print(type(my_str)) -- "string"

local my_func = function() end
print(type(my_func)) -- "function"

Dofile & Loadfile

-- Using dofile
dofile("my_file.lua") -- Executes my_file.lua immediately

-- Using loadfile
local my_func = loadfile("my_file.lua")
if my_func then
  -- my_file.lua is valid, now execute it
  my_func()
else
  print("Error loading file.")
end

Pairs

local my_table = {10, "hello", 20, name = "Lua"}

print("Using pairs:")
for key, value in pairs(my_table) do
  print(key, value)
end

print("Using ipairs:")
for key, value in ipairs(my_table) do
  print(key, value)
end

To number

local num1 = tonumber("34")
print(num1, type(num1)) -- 34 number

local num2 = tonumber("34.5")
print(num2, type(num2)) -- 34.5 number

local num3 = tonumber("abc")
print(num3) -- nil (conversion failed)

local hex_num = tonumber("8f", 16)
print(hex_num) -- 143 (8 * 16 + 15)

#字符串 (Strings)

s = "Hello"

Concatenation

s .. " there" -- => Hello there

Commonly used methods

s:upper() -- => HELLO
s:lower() -- => hello
s:len()   -- => 5
s:find("o") -- => 5
s:reverse() -- => olleH

Sub

local s = "programming"
s:sub(3, 7) -- (extracts substring) => "ogram"

Gsub

s:gsub() --> (substitutes all matches)

Char

s = "ha"
s:rep(3) -- // repeats 3 times -> "hahaha"
local s_char = string.char(72, 101, 108, 108, 111)
print(s_char) -- "Hello"

Format

local name = "Alice"
local age = 30
local formatted = string.format("My name is %s and I am %d years old.", name, age)
print(formatted) -- "My name is Alice and I am 30 years old."

Others

s:match()
s:gmatch()
s:dump()
s:byte()

#placeholder

#入门指南

#简介 (Introduction)

#Hello World 示例


print("Hello, World!") -- Hello, World!

-- You can omit parentheses if the argument is one string or table literal
print "Hello, World!"  -- Hello, World!

print [[multi-line
 Hello
 World]]


Lua 经典 Hello World 示例

#变量声明 (Variables)


local age = 18 -- local variable
boys, girls = 2, 3 -- global variables

-- Now x = 1, y = 2, z = 3, and 4 is thrown away.
x, y, z = 1, 2, 3, 4

-- Undefined variables return nil.
-- This is not an error:
foo = anUnknownVariable  -- Now foo = nil.

-- Variables are global by default unless declared with local.

Lua is a dynamically typed language and hence only the values will have types not the variables.

#数据类型 (Data Types)

Value Type Description
number Represent (double-precision) numbers
string Represents text
nil Differentiates between values with data or not
boolean true or false value
function Represents a sub routine
userdata Represents arbitrary C data
thread Represents independent threads of execution
table key-value pair, or array.

See: Data Type APIs

#输入输出 (IO)

-- Writes data to the standard output or a file.
io.write("Enter your name: ")
-- Reads input from the user or a file. You can specify formats like "*l" (line), "*n" (number), or "*a" (all).
name = io.read()

io.write("Enter your age: ")
age = io.read()

#代码注释 (Comments)

-- This is a single line comments
--[[
 Comments (multi-line) could also be written like this
--]]

#运算符 (Operators)

#算术运算符 (Arithmetic)

-- add
  result = 10 + 30  -- => 40

-- subtract
result = 40 - 10  -- => 30

-- multiply
result = 50 * 5   -- => 250

-- divide (float division)
result = 16 / 4   -- => 4.0

-- divide (integer division, Lua 5.3+)
result = 16 // 4  -- => 4

-- modulo
result = 25 % 2   -- => 1

-- power
result = 5 ^ 3    -- => 125

-- unary minus
a = 12
result = -a -- => -12

#关系运算符 (Relational)

a = 10
b = 20

-- equals
print(a == b) -- false

-- not equals
print(a ~= b) -- true

-- greater than
print(a > b) -- false

-- less than
print(a < b) -- true

-- greater than or equals
print(a >= b) -- false

-- less than or equals
print(a <= b) -- true

#逻辑运算符 (Logical)

-- and
false and nil  --> false
0 and 20       --> 20
10 and 20      --> 20

-- or
true or false  --> true
10 or 0        --> 10
12 or 4        --> 12

  -- not
not true       --> false

Only nil and false are falsy; 0 and '' are true!

#条件控制 (Conditionals)

#if-else

num = 15
if num > 10 then
  print("num is greater than 10")
elseif num < 10 then
  print("num is smaller than 10")
else
  print("num is 10")
end

-- making a ternary operator
-- This is similar to the a?b:c operator in C/js:
ans = aBoolValue and 'yes' or 'no'  --> 'no'

#Loops

#While loop

i = 1
while i <= 5 do
  print(i)
  i = i + 1
end

#For loop

-- Numeric for loop (start, end, step)
for i = 1, 5, 1 do
  print(i)
end

-- Generic for loop for tables
t = {10, 20, 30}
for k, v in ipairs(t) do
  print(k, v) -- prints 1 10, 2 20, 3 30
end

#Repeat-until loop

i = 1
repeat
  print(i)
  i = i + 1
until i > 5

#Breaking out

while x do
  if condition then
    break
  end
end

#Continue

-- prints even numbers in [|1,10|]
for i=1,10 do
   if i % 2 == 1 then
    goto continue
  end
   print(i)
   ::continue::
end

#Functions

#Creating fns

function myFunction()
  return 1
end

function myFunctionWithArgs(a, b)
  -- ...
end

-- function as arg
function operate(a, b, func)
    return func(a, b)
end



-- anonymous function
function (parameters)
    -- body of the function
end


local greet = function(name)
    return "Hello, " .. name
end


-- Not exported in the module
local function myPrivateFunction()
end


-- Splats
function doAction(action, ...)
  print("Doing '"..action.."' to", ...)
end

#Invoking fns

myFunction()

print(greet("Lua")) -- Output: Hello, Lua


-- function as arg
local result = operate(5, 3, function(x, y)
    return x + y
end)

print(result) -- Output: 8


doAction('write', "Shirley", "Abed")
--> Doing 'write' to Shirley Abed

You can omit parentheses if the argument is one string or table literal

print "Hello World"     -->     print("Hello World")

dofile 'a.lua'          -->     dofile ('a.lua')

print [[a multi-line    -->     print([[a multi-line
 message]]                        message]])

f{x=10, y=20}           -->     f({x=10, y=20})

type{}                  -->     type({})

#Data Type APIs

#Global functions

Assert

local my_table = {}
assert(my_table, "my_table should exist!") -- This will not fail

local a = nil
-- This will cause a runtime error with the message "a is nil"
assert(a, "a is nil")

Type

local my_var = 10
print(type(my_var)) -- "number"

local my_str = "hello"
print(type(my_str)) -- "string"

local my_func = function() end
print(type(my_func)) -- "function"

Dofile & Loadfile

-- Using dofile
dofile("my_file.lua") -- Executes my_file.lua immediately

-- Using loadfile
local my_func = loadfile("my_file.lua")
if my_func then
  -- my_file.lua is valid, now execute it
  my_func()
else
  print("Error loading file.")
end

Pairs

local my_table = {10, "hello", 20, name = "Lua"}

print("Using pairs:")
for key, value in pairs(my_table) do
  print(key, value)
end

print("Using ipairs:")
for key, value in ipairs(my_table) do
  print(key, value)
end

To number

local num1 = tonumber("34")
print(num1, type(num1)) -- 34 number

local num2 = tonumber("34.5")
print(num2, type(num2)) -- 34.5 number

local num3 = tonumber("abc")
print(num3) -- nil (conversion failed)

local hex_num = tonumber("8f", 16)
print(hex_num) -- 143 (8 * 16 + 15)

#字符串 (Strings)

s = "Hello"

Concatenation

s .. " there" -- => Hello there

Commonly used methods

s:upper() -- => HELLO
s:lower() -- => hello
s:len()   -- => 5
s:find("o") -- => 5
s:reverse() -- => olleH

Sub

local s = "programming"
s:sub(3, 7) -- (extracts substring) => "ogram"

Gsub

s:gsub() --> (substitutes all matches)

Char

s = "ha"
s:rep(3) -- // repeats 3 times -> "hahaha"
local s_char = string.char(72, 101, 108, 108, 111)
print(s_char) -- "Hello"

Format

local name = "Alice"
local age = 30
local formatted = string.format("My name is %s and I am %d years old.", name, age)
print(formatted) -- "My name is Alice and I am 30 years old."

Others

s:match()
s:gmatch()
s:dump()
s:byte()

#placeholder

#入门指南

#简介 (Introduction)

#Hello World 示例


print("Hello, World!") -- Hello, World!

-- You can omit parentheses if the argument is one string or table literal
print "Hello, World!"  -- Hello, World!

print [[multi-line
 Hello
 World]]


Lua 经典 Hello World 示例

#变量声明 (Variables)


local age = 18 -- local variable
boys, girls = 2, 3 -- global variables

-- Now x = 1, y = 2, z = 3, and 4 is thrown away.
x, y, z = 1, 2, 3, 4

-- Undefined variables return nil.
-- This is not an error:
foo = anUnknownVariable  -- Now foo = nil.

-- Variables are global by default unless declared with local.

Lua is a dynamically typed language and hence only the values will have types not the variables.

#数据类型 (Data Types)

Value Type Description
number Represent (double-precision) numbers
string Represents text
nil Differentiates between values with data or not
boolean true or false value
function Represents a sub routine
userdata Represents arbitrary C data
thread Represents independent threads of execution
table key-value pair, or array.

See: Data Type APIs

#输入输出 (IO)

-- Writes data to the standard output or a file.
io.write("Enter your name: ")
-- Reads input from the user or a file. You can specify formats like "*l" (line), "*n" (number), or "*a" (all).
name = io.read()

io.write("Enter your age: ")
age = io.read()

#代码注释 (Comments)

-- This is a single line comments
--[[
 Comments (multi-line) could also be written like this
--]]

#运算符 (Operators)

#算术运算符 (Arithmetic)

-- add
  result = 10 + 30  -- => 40

-- subtract
result = 40 - 10  -- => 30

-- multiply
result = 50 * 5   -- => 250

-- divide (float division)
result = 16 / 4   -- => 4.0

-- divide (integer division, Lua 5.3+)
result = 16 // 4  -- => 4

-- modulo
result = 25 % 2   -- => 1

-- power
result = 5 ^ 3    -- => 125

-- unary minus
a = 12
result = -a -- => -12

#关系运算符 (Relational)

a = 10
b = 20

-- equals
print(a == b) -- false

-- not equals
print(a ~= b) -- true

-- greater than
print(a > b) -- false

-- less than
print(a < b) -- true

-- greater than or equals
print(a >= b) -- false

-- less than or equals
print(a <= b) -- true

#逻辑运算符 (Logical)

-- and
false and nil  --> false
0 and 20       --> 20
10 and 20      --> 20

-- or
true or false  --> true
10 or 0        --> 10
12 or 4        --> 12

  -- not
not true       --> false

Only nil and false are falsy; 0 and '' are true!

#条件控制 (Conditionals)

#if-else

num = 15
if num > 10 then
  print("num is greater than 10")
elseif num < 10 then
  print("num is smaller than 10")
else
  print("num is 10")
end

-- making a ternary operator
-- This is similar to the a?b:c operator in C/js:
ans = aBoolValue and 'yes' or 'no'  --> 'no'

#Loops

#While loop

i = 1
while i <= 5 do
  print(i)
  i = i + 1
end

#For loop

-- Numeric for loop (start, end, step)
for i = 1, 5, 1 do
  print(i)
end

-- Generic for loop for tables
t = {10, 20, 30}
for k, v in ipairs(t) do
  print(k, v) -- prints 1 10, 2 20, 3 30
end

#Repeat-until loop

i = 1
repeat
  print(i)
  i = i + 1
until i > 5

#Breaking out

while x do
  if condition then
    break
  end
end

#Continue

-- prints even numbers in [|1,10|]
for i=1,10 do
   if i % 2 == 1 then
    goto continue
  end
   print(i)
   ::continue::
end

#Functions

#Creating fns

function myFunction()
  return 1
end

function myFunctionWithArgs(a, b)
  -- ...
end

-- function as arg
function operate(a, b, func)
    return func(a, b)
end



-- anonymous function
function (parameters)
    -- body of the function
end


local greet = function(name)
    return "Hello, " .. name
end


-- Not exported in the module
local function myPrivateFunction()
end


-- Splats
function doAction(action, ...)
  print("Doing '"..action.."' to", ...)
end

#Invoking fns

myFunction()

print(greet("Lua")) -- Output: Hello, Lua


-- function as arg
local result = operate(5, 3, function(x, y)
    return x + y
end)

print(result) -- Output: 8


doAction('write', "Shirley", "Abed")
--> Doing 'write' to Shirley Abed

You can omit parentheses if the argument is one string or table literal

print "Hello World"     -->     print("Hello World")

dofile 'a.lua'          -->     dofile ('a.lua')

print [[a multi-line    -->     print([[a multi-line
 message]]                        message]])

f{x=10, y=20}           -->     f({x=10, y=20})

type{}                  -->     type({})

#Data Type APIs

#Global functions

Assert

local my_table = {}
assert(my_table, "my_table should exist!") -- This will not fail

local a = nil
-- This will cause a runtime error with the message "a is nil"
assert(a, "a is nil")

Type

local my_var = 10
print(type(my_var)) -- "number"

local my_str = "hello"
print(type(my_str)) -- "string"

local my_func = function() end
print(type(my_func)) -- "function"

Dofile & Loadfile

-- Using dofile
dofile("my_file.lua") -- Executes my_file.lua immediately

-- Using loadfile
local my_func = loadfile("my_file.lua")
if my_func then
  -- my_file.lua is valid, now execute it
  my_func()
else
  print("Error loading file.")
end

Pairs

local my_table = {10, "hello", 20, name = "Lua"}

print("Using pairs:")
for key, value in pairs(my_table) do
  print(key, value)
end

print("Using ipairs:")
for key, value in ipairs(my_table) do
  print(key, value)
end

To number

local num1 = tonumber("34")
print(num1, type(num1)) -- 34 number

local num2 = tonumber("34.5")
print(num2, type(num2)) -- 34.5 number

local num3 = tonumber("abc")
print(num3) -- nil (conversion failed)

local hex_num = tonumber("8f", 16)
print(hex_num) -- 143 (8 * 16 + 15)

#字符串 (Strings)

s = "Hello"

Concatenation

s .. " there" -- => Hello there

Commonly used methods

s:upper() -- => HELLO
s:lower() -- => hello
s:len()   -- => 5
s:find("o") -- => 5
s:reverse() -- => olleH

Sub

local s = "programming"
s:sub(3, 7) -- (extracts substring) => "ogram"

Gsub

s:gsub() --> (substitutes all matches)

Char

s = "ha"
s:rep(3) -- // repeats 3 times -> "hahaha"
local s_char = string.char(72, 101, 108, 108, 111)
print(s_char) -- "Hello"

Format

local name = "Alice"
local age = 30
local formatted = string.format("My name is %s and I am %d years old.", name, age)
print(formatted) -- "My name is Alice and I am 30 years old."

Others

s:match()
s:gmatch()
s:dump()
s:byte()

#placeholder

#入门指南

#简介 (Introduction)

#Hello World 示例


print("Hello, World!") -- Hello, World!

-- You can omit parentheses if the argument is one string or table literal
print "Hello, World!"  -- Hello, World!

print [[multi-line
 Hello
 World]]


Lua 经典 Hello World 示例

#变量声明 (Variables)


local age = 18 -- local variable
boys, girls = 2, 3 -- global variables

-- Now x = 1, y = 2, z = 3, and 4 is thrown away.
x, y, z = 1, 2, 3, 4

-- Undefined variables return nil.
-- This is not an error:
foo = anUnknownVariable  -- Now foo = nil.

-- Variables are global by default unless declared with local.

Lua is a dynamically typed language and hence only the values will have types not the variables.

#数据类型 (Data Types)

Value Type Description
number Represent (double-precision) numbers
string Represents text
nil Differentiates between values with data or not
boolean true or false value
function Represents a sub routine
userdata Represents arbitrary C data
thread Represents independent threads of execution
table key-value pair, or array.

See: Data Type APIs

#输入输出 (IO)

-- Writes data to the standard output or a file.
io.write("Enter your name: ")
-- Reads input from the user or a file. You can specify formats like "*l" (line), "*n" (number), or "*a" (all).
name = io.read()

io.write("Enter your age: ")
age = io.read()

#代码注释 (Comments)

-- This is a single line comments
--[[
 Comments (multi-line) could also be written like this
--]]

#运算符 (Operators)

#算术运算符 (Arithmetic)

-- add
  result = 10 + 30  -- => 40

-- subtract
result = 40 - 10  -- => 30

-- multiply
result = 50 * 5   -- => 250

-- divide (float division)
result = 16 / 4   -- => 4.0

-- divide (integer division, Lua 5.3+)
result = 16 // 4  -- => 4

-- modulo
result = 25 % 2   -- => 1

-- power
result = 5 ^ 3    -- => 125

-- unary minus
a = 12
result = -a -- => -12

#关系运算符 (Relational)

a = 10
b = 20

-- equals
print(a == b) -- false

-- not equals
print(a ~= b) -- true

-- greater than
print(a > b) -- false

-- less than
print(a < b) -- true

-- greater than or equals
print(a >= b) -- false

-- less than or equals
print(a <= b) -- true

#逻辑运算符 (Logical)

-- and
false and nil  --> false
0 and 20       --> 20
10 and 20      --> 20

-- or
true or false  --> true
10 or 0        --> 10
12 or 4        --> 12

  -- not
not true       --> false

Only nil and false are falsy; 0 and '' are true!

#条件控制 (Conditionals)

#if-else

num = 15
if num > 10 then
  print("num is greater than 10")
elseif num < 10 then
  print("num is smaller than 10")
else
  print("num is 10")
end

-- making a ternary operator
-- This is similar to the a?b:c operator in C/js:
ans = aBoolValue and 'yes' or 'no'  --> 'no'

#Loops

#While loop

i = 1
while i <= 5 do
  print(i)
  i = i + 1
end

#For loop

-- Numeric for loop (start, end, step)
for i = 1, 5, 1 do
  print(i)
end

-- Generic for loop for tables
t = {10, 20, 30}
for k, v in ipairs(t) do
  print(k, v) -- prints 1 10, 2 20, 3 30
end

#Repeat-until loop

i = 1
repeat
  print(i)
  i = i + 1
until i > 5

#Breaking out

while x do
  if condition then
    break
  end
end

#Continue

-- prints even numbers in [|1,10|]
for i=1,10 do
   if i % 2 == 1 then
    goto continue
  end
   print(i)
   ::continue::
end

#Functions

#Creating fns

function myFunction()
  return 1
end

function myFunctionWithArgs(a, b)
  -- ...
end

-- function as arg
function operate(a, b, func)
    return func(a, b)
end



-- anonymous function
function (parameters)
    -- body of the function
end


local greet = function(name)
    return "Hello, " .. name
end


-- Not exported in the module
local function myPrivateFunction()
end


-- Splats
function doAction(action, ...)
  print("Doing '"..action.."' to", ...)
end

#Invoking fns

myFunction()

print(greet("Lua")) -- Output: Hello, Lua


-- function as arg
local result = operate(5, 3, function(x, y)
    return x + y
end)

print(result) -- Output: 8


doAction('write', "Shirley", "Abed")
--> Doing 'write' to Shirley Abed

You can omit parentheses if the argument is one string or table literal

print "Hello World"     -->     print("Hello World")

dofile 'a.lua'          -->     dofile ('a.lua')

print [[a multi-line    -->     print([[a multi-line
 message]]                        message]])

f{x=10, y=20}           -->     f({x=10, y=20})

type{}                  -->     type({})

#Data Type APIs

#Global functions

Assert

local my_table = {}
assert(my_table, "my_table should exist!") -- This will not fail

local a = nil
-- This will cause a runtime error with the message "a is nil"
assert(a, "a is nil")

Type

local my_var = 10
print(type(my_var)) -- "number"

local my_str = "hello"
print(type(my_str)) -- "string"

local my_func = function() end
print(type(my_func)) -- "function"

Dofile & Loadfile

-- Using dofile
dofile("my_file.lua") -- Executes my_file.lua immediately

-- Using loadfile
local my_func = loadfile("my_file.lua")
if my_func then
  -- my_file.lua is valid, now execute it
  my_func()
else
  print("Error loading file.")
end

Pairs

local my_table = {10, "hello", 20, name = "Lua"}

print("Using pairs:")
for key, value in pairs(my_table) do
  print(key, value)
end

print("Using ipairs:")
for key, value in ipairs(my_table) do
  print(key, value)
end

To number

local num1 = tonumber("34")
print(num1, type(num1)) -- 34 number

local num2 = tonumber("34.5")
print(num2, type(num2)) -- 34.5 number

local num3 = tonumber("abc")
print(num3) -- nil (conversion failed)

local hex_num = tonumber("8f", 16)
print(hex_num) -- 143 (8 * 16 + 15)

#字符串 (Strings)

s = "Hello"

Concatenation

s .. " there" -- => Hello there

Commonly used methods

s:upper() -- => HELLO
s:lower() -- => hello
s:len()   -- => 5
s:find("o") -- => 5
s:reverse() -- => olleH

Sub

local s = "programming"
s:sub(3, 7) -- (extracts substring) => "ogram"

Gsub

s:gsub() --> (substitutes all matches)

Char

s = "ha"
s:rep(3) -- // repeats 3 times -> "hahaha"
local s_char = string.char(72, 101, 108, 108, 111)
print(s_char) -- "Hello"

Format

local name = "Alice"
local age = 30
local formatted = string.format("My name is %s and I am %d years old.", name, age)
print(formatted) -- "My name is Alice and I am 30 years old."

Others

s:match()
s:gmatch()
s:dump()
s:byte()

#placeholder

#入门指南

#简介 (Introduction)

#Hello World 示例


print("Hello, World!") -- Hello, World!

-- You can omit parentheses if the argument is one string or table literal
print "Hello, World!"  -- Hello, World!

print [[multi-line
 Hello
 World]]


Lua 经典 Hello World 示例

#变量声明 (Variables)


local age = 18 -- local variable
boys, girls = 2, 3 -- global variables

-- Now x = 1, y = 2, z = 3, and 4 is thrown away.
x, y, z = 1, 2, 3, 4

-- Undefined variables return nil.
-- This is not an error:
foo = anUnknownVariable  -- Now foo = nil.

-- Variables are global by default unless declared with local.

Lua is a dynamically typed language and hence only the values will have types not the variables.

#数据类型 (Data Types)

Value Type Description
number Represent (double-precision) numbers
string Represents text
nil Differentiates between values with data or not
boolean true or false value
function Represents a sub routine
userdata Represents arbitrary C data
thread Represents independent threads of execution
table key-value pair, or array.

See: Data Type APIs

#输入输出 (IO)

-- Writes data to the standard output or a file.
io.write("Enter your name: ")
-- Reads input from the user or a file. You can specify formats like "*l" (line), "*n" (number), or "*a" (all).
name = io.read()

io.write("Enter your age: ")
age = io.read()

#代码注释 (Comments)

-- This is a single line comments
--[[
 Comments (multi-line) could also be written like this
--]]

#运算符 (Operators)

#算术运算符 (Arithmetic)

-- add
  result = 10 + 30  -- => 40

-- subtract
result = 40 - 10  -- => 30

-- multiply
result = 50 * 5   -- => 250

-- divide (float division)
result = 16 / 4   -- => 4.0

-- divide (integer division, Lua 5.3+)
result = 16 // 4  -- => 4

-- modulo
result = 25 % 2   -- => 1

-- power
result = 5 ^ 3    -- => 125

-- unary minus
a = 12
result = -a -- => -12

#关系运算符 (Relational)

a = 10
b = 20

-- equals
print(a == b) -- false

-- not equals
print(a ~= b) -- true

-- greater than
print(a > b) -- false

-- less than
print(a < b) -- true

-- greater than or equals
print(a >= b) -- false

-- less than or equals
print(a <= b) -- true

#逻辑运算符 (Logical)

-- and
false and nil  --> false
0 and 20       --> 20
10 and 20      --> 20

-- or
true or false  --> true
10 or 0        --> 10
12 or 4        --> 12

  -- not
not true       --> false

Only nil and false are falsy; 0 and '' are true!

#条件控制 (Conditionals)

#if-else

num = 15
if num > 10 then
  print("num is greater than 10")
elseif num < 10 then
  print("num is smaller than 10")
else
  print("num is 10")
end

-- making a ternary operator
-- This is similar to the a?b:c operator in C/js:
ans = aBoolValue and 'yes' or 'no'  --> 'no'

#Loops

#While loop

i = 1
while i <= 5 do
  print(i)
  i = i + 1
end

#For loop

-- Numeric for loop (start, end, step)
for i = 1, 5, 1 do
  print(i)
end

-- Generic for loop for tables
t = {10, 20, 30}
for k, v in ipairs(t) do
  print(k, v) -- prints 1 10, 2 20, 3 30
end

#Repeat-until loop

i = 1
repeat
  print(i)
  i = i + 1
until i > 5

#Breaking out

while x do
  if condition then
    break
  end
end

#Continue

-- prints even numbers in [|1,10|]
for i=1,10 do
   if i % 2 == 1 then
    goto continue
  end
   print(i)
   ::continue::
end

#Functions

#Creating fns

function myFunction()
  return 1
end

function myFunctionWithArgs(a, b)
  -- ...
end

-- function as arg
function operate(a, b, func)
    return func(a, b)
end



-- anonymous function
function (parameters)
    -- body of the function
end


local greet = function(name)
    return "Hello, " .. name
end


-- Not exported in the module
local function myPrivateFunction()
end


-- Splats
function doAction(action, ...)
  print("Doing '"..action.."' to", ...)
end

#Invoking fns

myFunction()

print(greet("Lua")) -- Output: Hello, Lua


-- function as arg
local result = operate(5, 3, function(x, y)
    return x + y
end)

print(result) -- Output: 8


doAction('write', "Shirley", "Abed")
--> Doing 'write' to Shirley Abed

You can omit parentheses if the argument is one string or table literal

print "Hello World"     -->     print("Hello World")

dofile 'a.lua'          -->     dofile ('a.lua')

print [[a multi-line    -->     print([[a multi-line
 message]]                        message]])

f{x=10, y=20}           -->     f({x=10, y=20})

type{}                  -->     type({})

#Data Type APIs

#Global functions

Assert

local my_table = {}
assert(my_table, "my_table should exist!") -- This will not fail

local a = nil
-- This will cause a runtime error with the message "a is nil"
assert(a, "a is nil")

Type

local my_var = 10
print(type(my_var)) -- "number"

local my_str = "hello"
print(type(my_str)) -- "string"

local my_func = function() end
print(type(my_func)) -- "function"

Dofile & Loadfile

-- Using dofile
dofile("my_file.lua") -- Executes my_file.lua immediately

-- Using loadfile
local my_func = loadfile("my_file.lua")
if my_func then
  -- my_file.lua is valid, now execute it
  my_func()
else
  print("Error loading file.")
end

Pairs

local my_table = {10, "hello", 20, name = "Lua"}

print("Using pairs:")
for key, value in pairs(my_table) do
  print(key, value)
end

print("Using ipairs:")
for key, value in ipairs(my_table) do
  print(key, value)
end

To number

local num1 = tonumber("34")
print(num1, type(num1)) -- 34 number

local num2 = tonumber("34.5")
print(num2, type(num2)) -- 34.5 number

local num3 = tonumber("abc")
print(num3) -- nil (conversion failed)

local hex_num = tonumber("8f", 16)
print(hex_num) -- 143 (8 * 16 + 15)

#字符串 (Strings)

s = "Hello"

Concatenation

s .. " there" -- => Hello there

Commonly used methods

s:upper() -- => HELLO
s:lower() -- => hello
s:len()   -- => 5
s:find("o") -- => 5
s:reverse() -- => olleH

Sub

local s = "programming"
s:sub(3, 7) -- (extracts substring) => "ogram"

Gsub

s:gsub() --> (substitutes all matches)

Char

s = "ha"
s:rep(3) -- // repeats 3 times -> "hahaha"
local s_char = string.char(72, 101, 108, 108, 111)
print(s_char) -- "Hello"

Format

local name = "Alice"
local age = 30
local formatted = string.format("My name is %s and I am %d years old.", name, age)
print(formatted) -- "My name is Alice and I am 30 years old."

Others

s:match()
s:gmatch()
s:dump()
s:byte()

#placeholder

#入门指南

#简介 (Introduction)

#Hello World 示例


print("Hello, World!") -- Hello, World!

-- You can omit parentheses if the argument is one string or table literal
print "Hello, World!"  -- Hello, World!

print [[multi-line
 Hello
 World]]


Lua 经典 Hello World 示例

#变量声明 (Variables)


local age = 18 -- local variable
boys, girls = 2, 3 -- global variables

-- Now x = 1, y = 2, z = 3, and 4 is thrown away.
x, y, z = 1, 2, 3, 4

-- Undefined variables return nil.
-- This is not an error:
foo = anUnknownVariable  -- Now foo = nil.

-- Variables are global by default unless declared with local.

Lua is a dynamically typed language and hence only the values will have types not the variables.

#数据类型 (Data Types)

Value Type Description
number Represent (double-precision) numbers
string Represents text
nil Differentiates between values with data or not
boolean true or false value
function Represents a sub routine
userdata Represents arbitrary C data
thread Represents independent threads of execution
table key-value pair, or array.

See: Data Type APIs

#输入输出 (IO)

-- Writes data to the standard output or a file.
io.write("Enter your name: ")
-- Reads input from the user or a file. You can specify formats like "*l" (line), "*n" (number), or "*a" (all).
name = io.read()

io.write("Enter your age: ")
age = io.read()

#代码注释 (Comments)

-- This is a single line comments
--[[
 Comments (multi-line) could also be written like this
--]]

#运算符 (Operators)

#算术运算符 (Arithmetic)

-- add
  result = 10 + 30  -- => 40

-- subtract
result = 40 - 10  -- => 30

-- multiply
result = 50 * 5   -- => 250

-- divide (float division)
result = 16 / 4   -- => 4.0

-- divide (integer division, Lua 5.3+)
result = 16 // 4  -- => 4

-- modulo
result = 25 % 2   -- => 1

-- power
result = 5 ^ 3    -- => 125

-- unary minus
a = 12
result = -a -- => -12

#关系运算符 (Relational)

a = 10
b = 20

-- equals
print(a == b) -- false

-- not equals
print(a ~= b) -- true

-- greater than
print(a > b) -- false

-- less than
print(a < b) -- true

-- greater than or equals
print(a >= b) -- false

-- less than or equals
print(a <= b) -- true

#逻辑运算符 (Logical)

-- and
false and nil  --> false
0 and 20       --> 20
10 and 20      --> 20

-- or
true or false  --> true
10 or 0        --> 10
12 or 4        --> 12

  -- not
not true       --> false

Only nil and false are falsy; 0 and '' are true!

#条件控制 (Conditionals)

#if-else

num = 15
if num > 10 then
  print("num is greater than 10")
elseif num < 10 then
  print("num is smaller than 10")
else
  print("num is 10")
end

-- making a ternary operator
-- This is similar to the a?b:c operator in C/js:
ans = aBoolValue and 'yes' or 'no'  --> 'no'

#Loops

#While loop

i = 1
while i <= 5 do
  print(i)
  i = i + 1
end

#For loop

-- Numeric for loop (start, end, step)
for i = 1, 5, 1 do
  print(i)
end

-- Generic for loop for tables
t = {10, 20, 30}
for k, v in ipairs(t) do
  print(k, v) -- prints 1 10, 2 20, 3 30
end

#Repeat-until loop

i = 1
repeat
  print(i)
  i = i + 1
until i > 5

#Breaking out

while x do
  if condition then
    break
  end
end

#Continue

-- prints even numbers in [|1,10|]
for i=1,10 do
   if i % 2 == 1 then
    goto continue
  end
   print(i)
   ::continue::
end

#Functions

#Creating fns

function myFunction()
  return 1
end

function myFunctionWithArgs(a, b)
  -- ...
end

-- function as arg
function operate(a, b, func)
    return func(a, b)
end



-- anonymous function
function (parameters)
    -- body of the function
end


local greet = function(name)
    return "Hello, " .. name
end


-- Not exported in the module
local function myPrivateFunction()
end


-- Splats
function doAction(action, ...)
  print("Doing '"..action.."' to", ...)
end

#Invoking fns

myFunction()

print(greet("Lua")) -- Output: Hello, Lua


-- function as arg
local result = operate(5, 3, function(x, y)
    return x + y
end)

print(result) -- Output: 8


doAction('write', "Shirley", "Abed")
--> Doing 'write' to Shirley Abed

You can omit parentheses if the argument is one string or table literal

print "Hello World"     -->     print("Hello World")

dofile 'a.lua'          -->     dofile ('a.lua')

print [[a multi-line    -->     print([[a multi-line
 message]]                        message]])

f{x=10, y=20}           -->     f({x=10, y=20})

type{}                  -->     type({})

#Data Type APIs

#Global functions

Assert

local my_table = {}
assert(my_table, "my_table should exist!") -- This will not fail

local a = nil
-- This will cause a runtime error with the message "a is nil"
assert(a, "a is nil")

Type

local my_var = 10
print(type(my_var)) -- "number"

local my_str = "hello"
print(type(my_str)) -- "string"

local my_func = function() end
print(type(my_func)) -- "function"

Dofile & Loadfile

-- Using dofile
dofile("my_file.lua") -- Executes my_file.lua immediately

-- Using loadfile
local my_func = loadfile("my_file.lua")
if my_func then
  -- my_file.lua is valid, now execute it
  my_func()
else
  print("Error loading file.")
end

Pairs

local my_table = {10, "hello", 20, name = "Lua"}

print("Using pairs:")
for key, value in pairs(my_table) do
  print(key, value)
end

print("Using ipairs:")
for key, value in ipairs(my_table) do
  print(key, value)
end

To number

local num1 = tonumber("34")
print(num1, type(num1)) -- 34 number

local num2 = tonumber("34.5")
print(num2, type(num2)) -- 34.5 number

local num3 = tonumber("abc")
print(num3) -- nil (conversion failed)

local hex_num = tonumber("8f", 16)
print(hex_num) -- 143 (8 * 16 + 15)

#字符串 (Strings)

s = "Hello"

Concatenation

s .. " there" -- => Hello there

Commonly used methods

s:upper() -- => HELLO
s:lower() -- => hello
s:len()   -- => 5
s:find("o") -- => 5
s:reverse() -- => olleH

Sub

local s = "programming"
s:sub(3, 7) -- (extracts substring) => "ogram"

Gsub

s:gsub() --> (substitutes all matches)

Char

s = "ha"
s:rep(3) -- // repeats 3 times -> "hahaha"
local s_char = string.char(72, 101, 108, 108, 111)
print(s_char) -- "Hello"

Format

local name = "Alice"
local age = 30
local formatted = string.format("My name is %s and I am %d years old.", name, age)
print(formatted) -- "My name is Alice and I am 30 years old."

Others

s:match()
s:gmatch()
s:dump()
s:byte()

#placeholder

#入门指南

#简介 (Introduction)

#Hello World 示例


print("Hello, World!") -- Hello, World!

-- You can omit parentheses if the argument is one string or table literal
print "Hello, World!"  -- Hello, World!

print [[multi-line
 Hello
 World]]


Lua 经典 Hello World 示例

#变量声明 (Variables)


local age = 18 -- local variable
boys, girls = 2, 3 -- global variables

-- Now x = 1, y = 2, z = 3, and 4 is thrown away.
x, y, z = 1, 2, 3, 4

-- Undefined variables return nil.
-- This is not an error:
foo = anUnknownVariable  -- Now foo = nil.

-- Variables are global by default unless declared with local.

Lua is a dynamically typed language and hence only the values will have types not the variables.

#数据类型 (Data Types)

Value Type Description
number Represent (double-precision) numbers
string Represents text
nil Differentiates between values with data or not
boolean true or false value
function Represents a sub routine
userdata Represents arbitrary C data
thread Represents independent threads of execution
table key-value pair, or array.

See: Data Type APIs

#输入输出 (IO)

-- Writes data to the standard output or a file.
io.write("Enter your name: ")
-- Reads input from the user or a file. You can specify formats like "*l" (line), "*n" (number), or "*a" (all).
name = io.read()

io.write("Enter your age: ")
age = io.read()

#代码注释 (Comments)

-- This is a single line comments
--[[
 Comments (multi-line) could also be written like this
--]]

#运算符 (Operators)

#算术运算符 (Arithmetic)

-- add
  result = 10 + 30  -- => 40

-- subtract
result = 40 - 10  -- => 30

-- multiply
result = 50 * 5   -- => 250

-- divide (float division)
result = 16 / 4   -- => 4.0

-- divide (integer division, Lua 5.3+)
result = 16 // 4  -- => 4

-- modulo
result = 25 % 2   -- => 1

-- power
result = 5 ^ 3    -- => 125

-- unary minus
a = 12
result = -a -- => -12

#关系运算符 (Relational)

a = 10
b = 20

-- equals
print(a == b) -- false

-- not equals
print(a ~= b) -- true

-- greater than
print(a > b) -- false

-- less than
print(a < b) -- true

-- greater than or equals
print(a >= b) -- false

-- less than or equals
print(a <= b) -- true

#逻辑运算符 (Logical)

-- and
false and nil  --> false
0 and 20       --> 20
10 and 20      --> 20

-- or
true or false  --> true
10 or 0        --> 10
12 or 4        --> 12

  -- not
not true       --> false

Only nil and false are falsy; 0 and '' are true!

#条件控制 (Conditionals)

#if-else

num = 15
if num > 10 then
  print("num is greater than 10")
elseif num < 10 then
  print("num is smaller than 10")
else
  print("num is 10")
end

-- making a ternary operator
-- This is similar to the a?b:c operator in C/js:
ans = aBoolValue and 'yes' or 'no'  --> 'no'

#Loops

#While loop

i = 1
while i <= 5 do
  print(i)
  i = i + 1
end

#For loop

-- Numeric for loop (start, end, step)
for i = 1, 5, 1 do
  print(i)
end

-- Generic for loop for tables
t = {10, 20, 30}
for k, v in ipairs(t) do
  print(k, v) -- prints 1 10, 2 20, 3 30
end

#Repeat-until loop

i = 1
repeat
  print(i)
  i = i + 1
until i > 5

#Breaking out

while x do
  if condition then
    break
  end
end

#Continue

-- prints even numbers in [|1,10|]
for i=1,10 do
   if i % 2 == 1 then
    goto continue
  end
   print(i)
   ::continue::
end

#Functions

#Creating fns

function myFunction()
  return 1
end

function myFunctionWithArgs(a, b)
  -- ...
end

-- function as arg
function operate(a, b, func)
    return func(a, b)
end



-- anonymous function
function (parameters)
    -- body of the function
end


local greet = function(name)
    return "Hello, " .. name
end


-- Not exported in the module
local function myPrivateFunction()
end


-- Splats
function doAction(action, ...)
  print("Doing '"..action.."' to", ...)
end

#Invoking fns

myFunction()

print(greet("Lua")) -- Output: Hello, Lua


-- function as arg
local result = operate(5, 3, function(x, y)
    return x + y
end)

print(result) -- Output: 8


doAction('write', "Shirley", "Abed")
--> Doing 'write' to Shirley Abed

You can omit parentheses if the argument is one string or table literal

print "Hello World"     -->     print("Hello World")

dofile 'a.lua'          -->     dofile ('a.lua')

print [[a multi-line    -->     print([[a multi-line
 message]]                        message]])

f{x=10, y=20}           -->     f({x=10, y=20})

type{}                  -->     type({})

#Data Type APIs

#Global functions

Assert

local my_table = {}
assert(my_table, "my_table should exist!") -- This will not fail

local a = nil
-- This will cause a runtime error with the message "a is nil"
assert(a, "a is nil")

Type

local my_var = 10
print(type(my_var)) -- "number"

local my_str = "hello"
print(type(my_str)) -- "string"

local my_func = function() end
print(type(my_func)) -- "function"

Dofile & Loadfile

-- Using dofile
dofile("my_file.lua") -- Executes my_file.lua immediately

-- Using loadfile
local my_func = loadfile("my_file.lua")
if my_func then
  -- my_file.lua is valid, now execute it
  my_func()
else
  print("Error loading file.")
end

Pairs

local my_table = {10, "hello", 20, name = "Lua"}

print("Using pairs:")
for key, value in pairs(my_table) do
  print(key, value)
end

print("Using ipairs:")
for key, value in ipairs(my_table) do
  print(key, value)
end

To number

local num1 = tonumber("34")
print(num1, type(num1)) -- 34 number

local num2 = tonumber("34.5")
print(num2, type(num2)) -- 34.5 number

local num3 = tonumber("abc")
print(num3) -- nil (conversion failed)

local hex_num = tonumber("8f", 16)
print(hex_num) -- 143 (8 * 16 + 15)

#字符串 (Strings)

s = "Hello"

Concatenation

s .. " there" -- => Hello there

Commonly used methods

s:upper() -- => HELLO
s:lower() -- => hello
s:len()   -- => 5
s:find("o") -- => 5
s:reverse() -- => olleH

Sub

local s = "programming"
s:sub(3, 7) -- (extracts substring) => "ogram"

Gsub

s:gsub() --> (substitutes all matches)

Char

s = "ha"
s:rep(3) -- // repeats 3 times -> "hahaha"
local s_char = string.char(72, 101, 108, 108, 111)
print(s_char) -- "Hello"

Format

local name = "Alice"
local age = 30
local formatted = string.format("My name is %s and I am %d years old.", name, age)
print(formatted) -- "My name is Alice and I am 30 years old."

Others

s:match()
s:gmatch()
s:dump()
s:byte()

#placeholder

#入门指南

#简介 (Introduction)

#Hello World 示例


print("Hello, World!") -- Hello, World!

-- You can omit parentheses if the argument is one string or table literal
print "Hello, World!"  -- Hello, World!

print [[multi-line
 Hello
 World]]


Lua 经典 Hello World 示例

#变量声明 (Variables)


local age = 18 -- local variable
boys, girls = 2, 3 -- global variables

-- Now x = 1, y = 2, z = 3, and 4 is thrown away.
x, y, z = 1, 2, 3, 4

-- Undefined variables return nil.
-- This is not an error:
foo = anUnknownVariable  -- Now foo = nil.

-- Variables are global by default unless declared with local.

Lua is a dynamically typed language and hence only the values will have types not the variables.

#数据类型 (Data Types)

Value Type Description
number Represent (double-precision) numbers
string Represents text
nil Differentiates between values with data or not
boolean true or false value
function Represents a sub routine
userdata Represents arbitrary C data
thread Represents independent threads of execution
table key-value pair, or array.

See: Data Type APIs

#输入输出 (IO)

-- Writes data to the standard output or a file.
io.write("Enter your name: ")
-- Reads input from the user or a file. You can specify formats like "*l" (line), "*n" (number), or "*a" (all).
name = io.read()

io.write("Enter your age: ")
age = io.read()

#代码注释 (Comments)

-- This is a single line comments
--[[
 Comments (multi-line) could also be written like this
--]]

#运算符 (Operators)

#算术运算符 (Arithmetic)

-- add
  result = 10 + 30  -- => 40

-- subtract
result = 40 - 10  -- => 30

-- multiply
result = 50 * 5   -- => 250

-- divide (float division)
result = 16 / 4   -- => 4.0

-- divide (integer division, Lua 5.3+)
result = 16 // 4  -- => 4

-- modulo
result = 25 % 2   -- => 1

-- power
result = 5 ^ 3    -- => 125

-- unary minus
a = 12
result = -a -- => -12

#关系运算符 (Relational)

a = 10
b = 20

-- equals
print(a == b) -- false

-- not equals
print(a ~= b) -- true

-- greater than
print(a > b) -- false

-- less than
print(a < b) -- true

-- greater than or equals
print(a >= b) -- false

-- less than or equals
print(a <= b) -- true

#逻辑运算符 (Logical)

-- and
false and nil  --> false
0 and 20       --> 20
10 and 20      --> 20

-- or
true or false  --> true
10 or 0        --> 10
12 or 4        --> 12

  -- not
not true       --> false

Only nil and false are falsy; 0 and '' are true!

#条件控制 (Conditionals)

#if-else

num = 15
if num > 10 then
  print("num is greater than 10")
elseif num < 10 then
  print("num is smaller than 10")
else
  print("num is 10")
end

-- making a ternary operator
-- This is similar to the a?b:c operator in C/js:
ans = aBoolValue and 'yes' or 'no'  --> 'no'

#Loops

#While loop

i = 1
while i <= 5 do
  print(i)
  i = i + 1
end

#For loop

-- Numeric for loop (start, end, step)
for i = 1, 5, 1 do
  print(i)
end

-- Generic for loop for tables
t = {10, 20, 30}
for k, v in ipairs(t) do
  print(k, v) -- prints 1 10, 2 20, 3 30
end

#Repeat-until loop

i = 1
repeat
  print(i)
  i = i + 1
until i > 5

#Breaking out

while x do
  if condition then
    break
  end
end

#Continue

-- prints even numbers in [|1,10|]
for i=1,10 do
   if i % 2 == 1 then
    goto continue
  end
   print(i)
   ::continue::
end

#Functions

#Creating fns

function myFunction()
  return 1
end

function myFunctionWithArgs(a, b)
  -- ...
end

-- function as arg
function operate(a, b, func)
    return func(a, b)
end



-- anonymous function
function (parameters)
    -- body of the function
end


local greet = function(name)
    return "Hello, " .. name
end


-- Not exported in the module
local function myPrivateFunction()
end


-- Splats
function doAction(action, ...)
  print("Doing '"..action.."' to", ...)
end

#Invoking fns

myFunction()

print(greet("Lua")) -- Output: Hello, Lua


-- function as arg
local result = operate(5, 3, function(x, y)
    return x + y
end)

print(result) -- Output: 8


doAction('write', "Shirley", "Abed")
--> Doing 'write' to Shirley Abed

You can omit parentheses if the argument is one string or table literal

print "Hello World"     -->     print("Hello World")

dofile 'a.lua'          -->     dofile ('a.lua')

print [[a multi-line    -->     print([[a multi-line
 message]]                        message]])

f{x=10, y=20}           -->     f({x=10, y=20})

type{}                  -->     type({})

#Data Type APIs

#Global functions

Assert

local my_table = {}
assert(my_table, "my_table should exist!") -- This will not fail

local a = nil
-- This will cause a runtime error with the message "a is nil"
assert(a, "a is nil")

Type

local my_var = 10
print(type(my_var)) -- "number"

local my_str = "hello"
print(type(my_str)) -- "string"

local my_func = function() end
print(type(my_func)) -- "function"

Dofile & Loadfile

-- Using dofile
dofile("my_file.lua") -- Executes my_file.lua immediately

-- Using loadfile
local my_func = loadfile("my_file.lua")
if my_func then
  -- my_file.lua is valid, now execute it
  my_func()
else
  print("Error loading file.")
end

Pairs

local my_table = {10, "hello", 20, name = "Lua"}

print("Using pairs:")
for key, value in pairs(my_table) do
  print(key, value)
end

print("Using ipairs:")
for key, value in ipairs(my_table) do
  print(key, value)
end

To number

local num1 = tonumber("34")
print(num1, type(num1)) -- 34 number

local num2 = tonumber("34.5")
print(num2, type(num2)) -- 34.5 number

local num3 = tonumber("abc")
print(num3) -- nil (conversion failed)

local hex_num = tonumber("8f", 16)
print(hex_num) -- 143 (8 * 16 + 15)

#字符串 (Strings)

s = "Hello"

Concatenation

s .. " there" -- => Hello there

Commonly used methods

s:upper() -- => HELLO
s:lower() -- => hello
s:len()   -- => 5
s:find("o") -- => 5
s:reverse() -- => olleH

Sub

local s = "programming"
s:sub(3, 7) -- (extracts substring) => "ogram"

Gsub

s:gsub() --> (substitutes all matches)

Char

s = "ha"
s:rep(3) -- // repeats 3 times -> "hahaha"
local s_char = string.char(72, 101, 108, 108, 111)
print(s_char) -- "Hello"

Format

local name = "Alice"
local age = 30
local formatted = string.format("My name is %s and I am %d years old.", name, age)
print(formatted) -- "My name is Alice and I am 30 years old."

Others

s:match()
s:gmatch()
s:dump()
s:byte()

#placeholder

math.acos(1) -- => 0
-- 返回 x 的反余弦值(弧度)。

math.asin(0) -- => 0
-- 返回 x 的反正弦值(弧度)。

math.atan(y, x)` -- => y/x 的反正切值
-- 返回 `y/x` 的反正切值(弧度),使用两个参数的符号来确定正确的象限。

math.ceil(x)` -- => 大于或等于 x 的最小整数
-- 返回不小于 `x` 的最小整数值。

math.cos(x)` -- => x 的余弦值
-- 返回 `x` 的余弦值(假定为弧度)。

math.deg(x)` -- => 弧度转角度
-- 返回角度 `x`(弧度)转换为角度。

math.exp(x)` -- => e^x
-- 返回 $e^x$ 的值,其中 $e$ 是自然对数的底。

math.floor(x)` -- => 小于或等于 x 的最大整数
-- 返回不大于 `x` 的最大整数值。

math.fmod(x, y)` -- => x 除以 y 的余数
-- 返回 `x` 除以 `y` 的余数,与 `x` 同号。

math.log(x, base)` -- => x 的对数
-- 返回 `x` 在给定 `base` 下的对数。如果未提供 `base`,默认为自然对数。

math.max(x, ...)` -- => 最大参数
-- 返回其参数中的最大值。

math.min(x, ...)` -- => 最小参数
-- 返回其参数中的最小值。

math.modf(x)` -- => 整数和小数部分
-- 返回两个数:`x` 的整数部分和小数部分。

math.pow(x, y)` -- => x^y
-- 返回 `x` 的 `y` 次方。

math.rad(x)` -- => 角度转弧度
-- 返回角度 `x`(角度)转换为弧度。

math.random(m, n)` -- => 随机数
-- 返回伪随机数。不带参数调用时,返回范围 $[0, 1)$ 内的浮点数。带一个参数 `n` 时,返回范围 $[1, n]$ 内的整数。带两个参数 `m` 和 `n` 时,返回范围 $[m, n]$ 内的整数。

math.sin(x)` -- => x 的正弦值
-- 返回 `x` 的正弦值(假定为弧度)。

math.sqrt(x)` -- => x 的平方根
-- 返回 `x` 的非负平方根。

math.tan(x)` -- => x 的正切值
-- 返回 `x` 的正切值(假定为弧度)。

#表基础 (Table basics)

-- 类数组表(从 1 开始索引)
local colors = {"red", "green", "blue"}
print(colors[1]) -- "red"

-- 类字典表
local user = {name = "Jane", age = 25}
print(user.name) -- "Jane"
print(user["age"]) -- 25

-- 混合表
local mixed = {1, "two", key = "value"}
print(mixed[1]) -- 1
print(mixed.key) -- "value"

-- 获取类数组表的长度
print(#colors) -- 3

#表操作 (Tables)

local my_table = {10, 20}

-- 插入(将 30 追加到末尾)
table.insert(my_table, 30)

-- 插入(在位置 1 插入 2)
table.insert(my_table, 1, 2)

-- 删除(删除位置 3 的项)
table.remove(my_table, 3)

-- 默认数值排序
local numbers = {5, 2, 8, 1}
table.sort(numbers) -- {1, 2, 5, 8}

-- 自定义降序排序
local numbers_desc = {5, 2, 8, 1}
table.sort(numbers_desc, function(a, b)
  return a > b
end) -- {8, 5, 2, 1}

-- 连接
local fruit = {"apple", "banana", "cherry"}
local fruit_string = table.concat(fruit, ", ")
print(fruit_string) -- apple, banana, cherry

#其他

#类 (Classes)

Lua 中没有内置类;可以使用表和元表以不同方式创建类。


简短说明;我们要做的基本上是创建一个可以保存数据和函数的表


Dog = {}

function Dog:new()
  newObj = {sound = 'woof'}
  self.__index = self
  return setmetatable(newObj, self)
end

function Dog:makeSound()
  print('I say ' .. self.sound)
end

mrDog = Dog:new()
mrDog:makeSound()  -- 'I say woof'

继承 (Inheritance)

LoudDog = Dog:new()

function LoudDog:makeSound()
  s = self.sound .. ' '
  print(s .. s .. s)
end

seymour = LoudDog:new()
seymour:makeSound()  -- 'woof woof woof'

另一个示例

Account = {}

function Account:new(balance)
  local t = setmetatable({}, { __index = Account })

  -- 你的构造函数内容
  t.balance = (balance or 0)
  return t
end

function Account:withdraw(amount)
  print("Withdrawing " .. amount .. "...")
  self.balance = self.balance - amount
  self:report()
end

function Account:report()
  print("Your current balance is: "..self.balance)
end

a = Account:new(9000)
a:withdraw(200)    -- 方法调用

#元表 (Meta-tables)

元表只是一个包含函数的表。

mt = {}

mt.__tostring = function() return "lol" end
mt.__add      = function(b) ... end       -- a + b
mt.__mul      = function(b) ... end       -- a * b
mt.__index    = function(k) ... end       -- 查找(a[k] 或 a.k)
mt.__newindex = function(k, v) ... end    -- 设置器(a[k] = v)

元表允许你覆盖另一个表的行为。


mytable = {}
setmetatable(mytable, mt)

print(myobject)

#📁 文件操作

local file = io.open("test.txt", "w")
if file then
  file:write("Hello from Lua!")
  io.close(file)
end

local file = io.open("test.txt", "r")
if file then
  local content = file:read("*a") -- read all content
  print(content)
  io.close(file)
end