Lua 是由 Roberto Ierusalimschy、Waldemar Celes 和 Luiz Henrique de Figueiredo 于 1993 年在巴西 PUC-Rio 大学创建的轻量级、可嵌入的脚本语言。Lua 的名字在葡萄牙语中意为"月亮"。
Lua 的核心定位是 轻量级、可嵌入的脚本语言。它提供了:
Lua 于 1993 年在巴西 PUC-Rio 大学创建,最初是作为数据描述语言。Lua 的设计目标是在 C/C++ 应用中嵌入,提供灵活的可扩展性。
-- 注释
-- 这是一个注释
-- 变量
name = "Lua" -- 全局变量
local age = 30 -- 局部变量(推荐)
-- 基本类型
print(type("hello")) -- string
print(type(10)) -- number
print(type(true)) -- boolean
print(type({})) -- table
print(type(nil)) -- nil
-- 字符串
local str = "Hello, Lua!"
local multiline = [[
多行字符串
]]
-- 数字
local integer = 42
local float = 3.14
-- 布尔值
local is_active = true
-- 表(Table)
local person = {
name = "Alice",
age = 30,
hobbies = {"reading", "coding"}
}
-- 访问表
print(person.name) -- 点访问
print(person["age"]) -- 索引访问
print(person.hobbies[1]) -- 数组索引
-- 函数
function greet(name)
return "Hello, " .. name .. "!"
end
-- 匿名函数
local add = function(a, b)
return a + b
end
-- if/else
local age = 18
if age >= 18 then
print("成年")
elseif age >= 13 then
print("青少年")
else
print("儿童")
end
-- while 循环
local i = 1
while i <= 5 do
print(i)
i = i + 1
end
-- for 循环(数值)
for i = 1, 10 do
print(i)
end
-- for 循环(步长)
for i = 10, 1, -1 do
print(i)
end
-- for 循环(迭代器)
local fruits = {"apple", "banana", "orange"}
for i, v in ipairs(fruits) do
print(i, v)
end
-- 表迭代器
local person = {name="Alice", age=30, city="Beijing"}
for key, value in pairs(person) do
print(key, value)
end
-- 可变参数
function sum(...)
local total = 0
for i, v in ipairs({...}) do
total = total + v
end
return total
end
print(sum(1, 2, 3, 4, 5)) -- 15
-- 闭包
function createCounter()
local count = 0
return function()
count = count + 1
return count
end
end
local counter = createCounter()
print(counter()) -- 1
print(counter()) -- 2
-- 尾递归
function factorial(n, acc)
acc = acc or 1
if n <= 0 then
return acc
else
return factorial(n - 1, n * acc)
end
end
-- 元表示例
local table1 = {1, 2, 3}
local table2 = {4, 5, 6}
-- 定义元方法
local mt = {
__add = function(a, b)
local result = {}
for i = 1, #a do
result[i] = a[i] + b[i]
end
return result
end,
__tostring = function(t)
return "{" .. table.concat(t, ", ") .. "}"
end
}
setmetatable(table1, mt)
setmetatable(table2, mt)
-- 使用 + 运算符(调用 __add)
local result = table1 + table2
print(result) -- {5, 7, 9}
-- 常用元方法
-- __index: 访问不存在的键时调用
-- __newindex: 添加新键时调用
-- __call: 将表作为函数调用
-- __len: # 运算符
-- 创建协程
local co = coroutine.create(function()
for i = 1, 5 do
print("协程: " .. i)
coroutine.yield(i)
end
return "完成"
end)
-- 恢复协程
while coroutine.status(co) ~= "dead" do
local status, result = coroutine.resume(co)
print("主程序: 收到", result)
end
// C 代码:嵌入 Lua
#include
#include
#include
int main() {
// 创建 Lua 状态机
lua_State *L = luaL_newstate();
luaL_openlibs(L);
// 执行 Lua 代码
luaL_dostring(L, "print('Hello from Lua!')");
// 调用 Lua 函数
lua_getglobal(L, "greet");
lua_pushstring(L, "World");
lua_pcall(L, 1, 0, 0);
// 关闭 Lua
lua_close(L);
return 0;
}
-- nginx.conf 中的 Lua 脚本
location /hello {
content_by_lua_block {
ngx.say("Hello, OpenResty!")
}
}
-- 复杂逻辑
location /api/users {
content_by_lua_block {
local redis = require("resty.redis")
local red = redis:new()
red:connect("127.0.0.1", 6379)
local res, err = red:get("user:123")
if res then
ngx.say(res)
else
ngx.say("User not found")
end
}
}
-- Redis 原子操作脚本
-- 实现分布式锁
local key = KEYS[1]
local value = ARGV[1]
local ttl = tonumber(ARGV[2])
-- 设置锁(仅当不存在)
if redis.call("setnx", key, value) == 1 then
redis.call("expire", key, ttl)
return 1
else
return 0
end
-- 原子递增并返回
local current = redis.call("incr", KEYS[1])
if current == 1 then
redis.call("expire", KEYS[1], ARGV[1])
end
return current
| 对比项 | Lua | Python | JavaScript |
|---|---|---|---|
| 体积 | ~200KB | ~30MB | ~10MB |
| 速度 | 极快 | 快 | 快 |
| 嵌入式 | ✅ 设计目标 | ❌ | ❌ |
| 游戏脚本 | ✅ 流行 | 较少 | 较少 |
| 学习曲线 | 平缓 | 平缓 | 平缓 |
| 适用场景 | 嵌入式脚本 | 通用开发 | Web 开发 |
Lua 语法、变量、数据类型、控制结构、函数
表(Table)、元表、协程、模块化
OpenResty 开发、Redis 脚本、游戏脚本
与 C/C++ 互操作、LuaJIT、性能优化
Lua 是嵌入式脚本领域的隐形冠军。
它用 极小的体积、高效的执行、简单的语法 服务了游戏开发、Web 服务器(OpenResty)、Redis 脚本等众多场景。Lua 是小而美的典范。
"Lua 是嵌入式的完美脚本语言。" 🌙