-- 多维数组(3x3矩阵)
local matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}
print(matrix[2][3]) --> 6
-- 面向对象编程(基于原型链)
local Animal = {name = "Animal"}
function Animal:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function Animal:speak() print(self.name.." makes sound") end
local Dog = Animal:new({name="Dog"})
function Dog:speak() print("Woof!") end
local dog = Dog:new()
dog:speak() --> "Woof!"
3. 协同程序(Coroutine)的异步模型
与线程的区别:
非抢占式调度,由程序主动让出控制权(coroutine.yield())
共享同一内存空间,上下文切换成本极低(约为线程的1/1000)
典型应用: -- 生产者-消费者模型
local function producer(c) for i=1,5 do print("生产:", i) coroutine.resume(c, i) os.sleep(1) -- 模拟生产耗时 end end local function consumer() local c = coroutine.create(function() while true do local _, num = coroutine.yield() print("消费:", num) end end) producer(c) end consumer() -- 输出: -- 生产: 1 → 消费: 1(1秒后) -- 生产: 2 → 消费: 2(1秒后) -- ...
二、语法体系详解(附对比与避坑指南)
1. 变量作用域规则
类型
声明方式
作用域
内存管理
全局变量
直接赋值
整个程序生命周期
需手动释放(谨慎使用)
局部变量
local关键字
所在语句块或函数体内
离开作用域自动回收
注意事项:
未声明的变量默认是全局变量(建议开启lua -e "print(_G['未声明变量'])"检查)
局部变量可通过do...end块创建独立作用域: do local secret = "private" -- 仅在此块内可见 end -- print(secret) --> 报错
2. 运算符优先级(从高到低)
优先级
运算符
结合性
示例
1
^
右结合
232 = 2(32) = 512
2
not # - (unary)
右结合
-a #table not true
3
* / %
左结合
6/2*3 = 9
4
+ -
左结合
5-3+2 = 4
5
.. (字符串连接)
左结合
"a".."b".."c" = "abc"
6
> < >= <= ~= ==
左结合
3~=4 → true
7
and
左结合
a and b and c
8
or
左结合
a or b or c
3. 流程控制高级技巧
嵌套循环优化
-- 低效写法(O(n²))
for i=1,100 do
for j=1,100 do
if i == j then print(i) end
end
end
-- 高效写法(提前break)
for i=1,100 do
local found = false
for j=1,100 do
if i == j then
print(i)
found = true
break -- 内层循环提前退出
end
end
if found then break end -- 外层循环提前退出
end
表达式中的if-else技巧
-- 常规写法
local status
if score > 90 then
status = "优秀"
elseif score > 80 then
status = "良好"
else
status = "合格"
end
-- 表达式写法(适用于简单逻辑)
local status = score > 90 and "优秀" or (score > 80 and "良好" or "合格")
三、实战项目:开发一个JSON解析器(附完整代码)
需求分析
支持解析基础数据类型:null/boolean/number/string
支持解析数组([])和对象({})
错误处理:非法字符、格式错误提示
实现思路
词法分析:将JSON字符串转换为标记流(token stream),识别字符串、数字、括号等
语法分析:递归下降解析器,根据JSON语法规则构建Lua表结构
错误处理:记录解析位置,抛出详细错误信息
核心代码
local json = {}
local tokenizer = require("tokenizer") -- 假设已实现词法分析器
function json.parse(str)
local tokens = tokenizer.tokenize(str)
local pos = 1
local function parse_value()
local token = tokens[pos]
if token.type == "string" then
pos = pos + 1
return token.value:gsub(`\(.-\)`, function(m) -- 处理转义字符
if m == "\"" then return "\""
elseif m == "\\" then return "\\"
elseif m == "n" then return "\n"
-- 其他转义字符处理...
else return m end
end)
elseif token.type == "number" then
pos = pos + 1
return tonumber(token.value)
elseif token.type == "true" then
pos = pos + 1
return true
elseif token.type == "false" then
pos = pos + 1
return false
elseif token.type == "null" then
pos = pos + 1
return nil
elseif token.type == "{" then
return parse_object()
elseif token.type == "[" then
return parse_array()
else
error("Unexpected token: "..token.type, 2)
end
end
local function parse_object()
pos = pos + 1 -- 跳过"{"
local obj = {}
if tokens[pos].type ~= "}" then
repeat
local key = parse_value()
if tokens[pos].type ~= ":" then
error("Missing colon after key", 2)
end
pos = pos + 1 -- 跳过":"
obj[key] = parse_value()
until tokens[pos].type == "," and (pos + 1 <= #tokens and tokens[pos+1].type ~= "}")
pos = pos + 1 -- 跳过"}"
end
return obj
end
-- 数组解析函数parse_array类似,此处省略...
return parse_value()
end
-- 使用示例
local json_str = '{"name": "Alice", "age": 30, "hobbies": ["reading", "music"]}'
local data = json.parse(json_str)
print(data.name) --> Alice
print(table.concat(data.hobbies, ",")) --> reading,music
Comments NOTHING