Skip to content

Lua 基本语法

主要用于 Redis Lua 脚本编写时的语法参考。

变量

lua
xiaoman = 'xmzs'           -- 全局变量(直接赋值)
local xiaoman = 'xmzs'     -- 局部变量(local 关键字)

Lua 注释用 --,多行注释用 --[[ ... --]]

条件语句

lua
if condition1 then
  -- ...
elseif condition2 then
  -- ...
else
  -- ...
end

循环

lua
-- for 循环
for i = 1, 10 do
  print(i)
end

-- while 循环
while condition do
  -- ...
end

-- 遍历 table
for key, val in pairs(t) do
  print(key, val)
end

Table(数组/字典)

lua
local arr = {1, 2, 3}               -- 数组(索引从 1 开始)
local obj = {name = 'xm', age = 18}  -- 字典

print(arr[1])          -- 1
print(obj['name'])     -- 'xm'
print(obj.name)        -- 'xm'(语法糖)

#arr                   -- 获取数组长度
table.insert(arr, 4)   -- 插入
table.remove(arr, 1)   -- 删除

函数

lua
function add(a, b)
  return a + b
end

Redis EVAL 中常用示例

lua
-- 限流脚本
local current = redis.call('GET', KEYS[1])
if current and tonumber(current) > tonumber(ARGV[1]) then
  return redis.call('DECR', KEYS[1])
end
return 0

Lua 中检查变量用 nilif a == nil then ... end