入门
基础与变量
Lua 变量默认是全局的;用 'local' 声明作用域内的局部变量。Lua 支持多重赋值。注释用 --(单行)和 --[[ ]](多行)。
-- comments start with --
print("Hello, World!")
-- variables (global by default)
x = 10
name = "Alice"
-- local variables
local y = 20
local z = x + y
-- multiple assignment
local a, b, c = 1, 2, 3
print(a, b, c) -- 1 2 3注释
单行注释以 -- 开头。多行注释用 --[[ ... ]]。长括号注释支持层级数字如 --[==[ ]==],可在其中包含 ]] 而不会提前结束。
-- single line comment
--[[ multi-line
comment block ]]
print("hi")
-- long-bracket comments can have = signs for nesting
--[==[ this is a comment with ]] inside ]==]
print("still runs")打印与输出
print() 会加换行并用制表符分隔参数;io.write() 写入原始文本,无分隔符也无换行。print() 会把 nil 显示为 'nil',而大多数操作遇到 nil 会报错。
print("Hello") -- prints with a trailing newline
io.write("no newline") -- writes without a newline
-- print separates multiple args with tabs
print("name", "age") -- name age
-- print converts all types (nil included)
print(42, true, nil) -- 42 true nil
-- io.stdout / io.stderr are file handles
io.stderr:write("warning\n")多重赋值
所有右值在赋值前先求值,因此能干净地交换变量。缺少的值变为 nil,多余的值被静默丢弃。列表会按变量数量调整。
local a, b = 1, 2
print(a, b) -- 1 2
a, b = b, a -- swap without a temp variable
print(a, b) -- 2 1
local x, y, z = 10 -- y, z become nil
local m, n = 1, 2, 3 -- 3 is discarded
print(m, n) -- 1 2交互模式
lua -i 启动交互式解释器。在 REPL 中给表达式加前缀 '=' 会求值并打印,类似 Python 的 REPL。用 'lua file.lua' 运行脚本,自上而下执行。
-- run the REPL: lua -i
-- run a file: lua script.lua
-- show the version: lua -v
-- inside the REPL:
-- > print("hi")
-- hi
-- > = 2 + 3 -- '=' prints an expression value
-- 5
-- > = string.rep("ab", 3)
-- abababnil 与变量删除
nil 是 Lua 唯一的'无值'类型。给表键赋 nil 会删除该键。访问未声明的全局变量会返回 nil 而不是报错,这可能掩盖拼写错误——可用 strict.lua 来捕获。
local x = 10
print(x) -- 10
x = nil -- delete the value
print(x) -- nil
if x == nil then
print("x is nil")
end
-- reading an undeclared name returns nil (no error)
print(undefined_var) -- nil
-- assign nil to let the GC collect a table entry
local t = {a = 1}
t.a = nil数据类型
八种基本类型
Lua 是动态类型;变量没有类型,只有值有。type() 返回标识值类型的小写字符串。8 种类型为 nil、boolean、number、string、table、function、thread、userdata。
-- Lua has 8 basic types:
print(type(nil)) -- nil
print(type(true)) -- boolean
print(type(42)) -- number
print(type("hi")) -- string
print(type({})) -- table
print(type(print)) -- function
print(type(coroutine.create(function() end))) -- thread
print(type(io.stdin)) -- userdata
-- type() always returns a string
print(type(type(42))) -- string数字
整数和浮点数都属于 'number' 类型;math.type() 可区分(Lua 5.3+)。'/' 始终做真除法(浮点),而 '//' 做向下取整除法,保留操作数类型。
-- Lua 5.3+ distinguishes integers and floats
local i = 10 -- integer
local f = 3.14 -- float
print(type(i), math.type(i)) -- number integer
print(type(f), math.type(f)) -- number float
local hex = 0xFF -- 255
local exp = 1e3 -- 1000.0 (float)
print(hex, exp)
-- integer / integer with no fraction stays integer
print(7 / 2) -- 3.5 (true division, always float)
print(7 // 2) -- 3 (floor division)字符串
单引号和双引号等价。长括号 [[ ]](或 [==[ ]==])创建原始多行字符串,其中转义序列不被处理。# 返回字节长度,而非字符数。
local s1 = "double quoted"
local s2 = 'single quoted' -- identical to double
local s3 = [[
a multi-line
string, escapes ignored]]
print(#s1) -- 14 (# is the length operator)
print(s1:upper()) -- DOUBLE QUOTED
-- strings are immutable: operations return new strings布尔值与真值
Lua 只有两个假值:nil 和 false。其他一切(包括 0 和空串)都为真。这与 C/Python 不同,是移植代码时常见的坑。
local flag = true
local done = false
-- ONLY nil and false are falsy
-- 0, "", and {} are all truthy (unlike many languages)
if 0 then print("0 is truthy") end
if "" then print("empty string is truthy") end
-- logical operators short-circuit and return a value
local x = nil or "default" -- "default"
local y = true and "yes" -- "yes"
print(x, y)表
表是关联数组,是 Lua 唯一的复合数据结构,兼作数组、记录、对象和模块。数组下标按约定从 1 开始。一张表可混合序列部分和哈希部分。
-- the table is Lua's only composite data structure
-- it serves as array, dictionary, object, and module
local arr = {10, 20, 30} -- array (1-indexed)
local dict = {name = "Lua", ver = 5.4}
local mixed = {1, 2, x = 3}
print(arr[1]) -- 10 (indices start at 1, not 0)
print(dict.name) -- Lua
print(mixed.x) -- 3
print(#arr) -- 3类型检查
type() 是按值类型分支判断的标准方式。它对 nil 返回 'nil' 而非报错。更细致的判断可用 math.type(整数 vs 浮点)或 rawequal 做同一性比较。
local function describe(v)
local t = type(v)
if t == "table" then
return "a table"
elseif t == "string" then
return "a string: " .. v
elseif t == "nil" then
return "nothing"
end
return "a " .. t
end
print(describe({})) -- a table
print(describe("hi")) -- a string: hi
print(describe(nil)) -- nothing运算符
算术运算符
Lua 支持 +、-、*、/、%、一元 - 和 ^。注意 ^ 是乘方(返回浮点),不是按位异或。没有自增(++)运算符;用 x = x + 1。
print(10 + 3) -- 13
print(10 - 3) -- 7
print(10 * 3) -- 30
print(10 / 3) -- 3.3333... (true division)
print(10 % 3) -- 1 (modulo)
print(2 ^ 10) -- 1024.0 (^ is exponent, NOT xor)
print(-5) -- -5 (unary minus)向下取整除法与取模
//(Lua 5.3+)向负无穷取整,不同于 C 的截断除法。% 运算定义为 a - floor(a/b)*b,因此结果总取除数的符号——适合做角度和下标的回绕。
-- Lua 5.3+ integer floor division
print(10 // 3) -- 3 (integer)
print(-10 // 3) -- -4 (floors toward -inf)
print(10.0 // 3) -- 3.0 (float floor div)
-- modulo result takes the sign of the divisor
print(10 % 3) -- 1
print(-10 % 3) -- 2
print(10 % -3) -- -2比较运算符
不等用 ~=(不是 !=)。不同类型的值用 == 或 ~= 比较总返回 false/true(nil == nil 除外);跨类型的排序比较会报错。字符串按字节序比较。
print(3 == 3) -- true (equality)
print(3 ~= 4) -- true (inequality: ~=, not !=)
print(3 < 4) -- true
print(3 > 4) -- false
print(3 <= 3) -- true
print(3 >= 4) -- false
print("abc" < "abd") -- true (lexicographic)
print(1 == "1") -- false (different types never equal)逻辑运算符
and 在第一操作数为假时返回它,否则返回第二操作数;or 在第一操作数为真时返回它,否则返回第二操作数。它们返回操作数,而非布尔值。(c) and x or y 这一惯用法在 x 为 false 或 nil 时会失效。
-- and / or / not short-circuit and return a value (not a bool)
print(true and 10) -- 10
print(false or "x") -- "x"
print(nil or "default") -- "default"
print(not nil) -- true
-- idiom for defaults
local name = nil
local display = name or "anonymous"
-- ternary-like (beware falsy 'false' values!)
local v = (cond) and "yes" or "no"字符串连接
.. 是唯一的连接运算符;它总是新建字符串(字符串不可变)。数字会自动转为字符串。拼接大字符串时,把片段收集到表里用 table.concat 比反复连接快得多。
local name = "Lua"
local v = 5.4
print("Hello " .. name .. " " .. v) -- Hello Lua 5.4
-- .. always creates a new string
local s = "a" .. "b" .. "c"
print(s) -- abc
-- numbers are auto-converted when concatenated
print("n=" .. 42) -- n=42
-- repeat a string with string.rep
print(string.rep("ab", 3)) -- ababab长度运算符
# 返回字符串的字节长度或表序列部分的长度。仅对无空洞(nil 间隙)的表才有明确定义。要按 UTF-8 字符计数可用 lua-utf8 或 utf8 库(Lua 5.3+)。
-- # works on strings and the sequence part of tables
print(#"hello") -- 5
print(#{10, 20, 30}) -- 3
-- caution: # only counts the contiguous sequence part
-- the result is UNDEFINED if the table has holes
local t = {1, 2, nil, 4}
print(#t) -- 2 or 4 (implementation-defined)
-- # on a string returns its byte length, not codepoints
print(#"cafe") -- 4
print(#"café") -- 5 (é is 2 bytes in UTF-8)控制结构
if-elseif-else
条件用 then ... end,括号可选。没有 switch 语句——改用 elseif 串联。每个 if、while、for 和函数体都必须用 end 闭合。
local score = 85
if score >= 90 then
print("A")
elseif score >= 80 then
print("B")
elseif score >= 70 then
print("C")
else
print("F")
end
-- keywords: if / then / elseif / else / end
-- parentheses around the condition are optionalwhile 循环
while do ... end 运行零次或多次。循环体是一个 do 块,因此其中声明的 local 作用域限于每次迭代。用 break 跳出最内层循环。
local i = 1
while i <= 5 do
print(i)
i = i + 1 -- Lua has no ++ operator
end
-- the condition is checked before each iteration
local n = 0
while n < 3 do
print("loop", n)
n = n + 1
endrepeat-until
repeat-until 是后测试循环,至少执行一次,条件为真时退出(与 while 相反)。与其他块不同,循环体中声明的 local 对 until 条件可见。
-- repeat-until runs the body at least once (like do-while)
-- the loop STOPS when the condition becomes true
local i = 1
repeat
print(i)
i = i + 1
until i > 5
-- the condition can see locals declared in the body
local x
repeat
x = math.random(1, 10)
until x == 7数值 for
数值 for 让 i 从 start 到 stop(含),每次加 step(默认 1)。循环变量在每次迭代都是全新的局部变量——对闭包安全。limit 和 step 在开始时只求值一次。
-- for start, stop[, step]
for i = 1, 5 do
print(i) -- 1 2 3 4 5
end
for i = 10, 1, -2 do
print(i) -- 10 8 6 4 2
end
-- step defaults to 1; the loop variable is local to the loop
for i = 1, 3 do print(i) end
-- print(i) -- i is out of scope here泛型 for
ipairs 遍历序列部分,遇第一个 nil 即止;pairs 遍历每个键/值对,顺序不定。任何迭代器函数(返回下一个值或 nil 停止)都可驱动泛型 for。
local arr = {"a", "b", "c"}
-- ipairs iterates the array (sequence) part, 1..n
for i, v in ipairs(arr) do
print(i, v) -- 1 a / 2 b / 3 c
end
local dict = {x = 1, y = 2}
-- pairs iterates ALL key/value pairs (order not guaranteed)
for k, v in pairs(dict) do
print(k, v)
endbreak 与 goto
break 只跳出最内层循环;没有 continue。用 goto 加标签跳过迭代,或改用函数加 return 重构。goto 不能跳入某个 local 的作用域。
-- break exits the innermost loop only
for i = 1, 10 do
if i == 5 then break end
print(i) -- 1 2 3 4
end
-- Lua has NO continue; emulate it with goto
for i = 1, 5 do
if i % 2 == 0 then goto continue end
print(i) -- 1 3 5
::continue::
end
-- goto jumps to a label ::name:: within the same scope字符串
字符串字面量与转义
双引号和单引号等价。转义序列(换行 \n、制表符 \t)只在引号字符串中生效。长括号 [[ ]] 或 [==[ ]==] 产生原始字符串,反斜杠是字面量——适合放正则类模式和文件路径。
local s1 = "double 'quoted'"
local s2 = 'single "quoted"'
local s3 = "line1\nline2\ttabbed"
local s4 = "percent: %d %%"
-- long brackets: escapes are NOT processed
local s5 = [[raw \n string, \t kept literal]]
print(s3, s5)长度与索引
# 返回字节长度。string.sub 用 1 起始下标;负数下标从末尾算。string.byte 返回数字码,string.char 由码构造字符串。
local s = "hello"
print(#s) -- 5 (byte length)
-- the string library is 1-indexed
print(s:sub(1, 3)) -- "hel"
print(s:sub(-2)) -- "lo" (negative = from end)
print(s:byte(1)) -- 104 (ASCII of 'h')
print(string.char(104, 105)) -- "hi"长字符串
长括号字符串保留内嵌换行并忽略转义序列。要在其中包含 ]],用相同层级如 [==[ ]==];闭合标记必须有相同数量的 = 号。