Lua 是动态类型语言,变量无需声明类型,类型在运行时确定。
| 类型 | 描述 | 示例 |
|---|
| 全局变量 | 默认所有变量都是全局的,存储在全局表 _G 中 | name = "Lua" |
| 局部变量 | 使用 local 关键字声明,作用域有限 | local count = 10 |
| 表字段 | 存储在表中的变量 | person.name = "John" |
-
local name = "Lua"
local version = 5.4
-
local a, b = 10, 20
print(a, b) -- 10 20
-
local x, y = 1, 2
x, y = y, x
print(x, y) -- 2 1
-
local _, value = string.find("Hello Lua", "Lua")
print(value) -- 7
-
local person = {
name = "John",
age = 30,
address = {
street = "Main St",
city = "New York"
}
}
-
print(person.name) -- John
print(person["age"]) -- 30
print(person.address.city) -- New York
-
global_var = "global"
function test()
-- 函数作用域
local local_var = "local"
print(local_var) -- local
print(global_var) -- global
end
test()
print(global_var) -- global
-
local x = 10
print(x) -- 10
if then
local x = 20
print(x) -- 20
end
print(x) -- 10
- 首先在当前作用域查找局部变量
- 然后在包含当前作用域的外部作用域查找
- 最后在全局表
_G 中查找
- 如果都找不到,返回
nil
-
local x = 10 -- 行尾注释
-
可以跨越多行
-
可以跨越多行
-
-
-
功能描述: 计算两个数的和
参数: a (number) - 第一个数
b (number) - 第二个数
返回值: (number) - 两个数的和
-
功能描述: 计算两个数的和
参数: a (number) - 第一个数
b (number) - 第二个数
返回值: (number) - 两个数的和
-
function add(a, b)
return a + b
end
local score = 85
if score >= 90 then
print("优秀")
elseif score >= 80 then
print("良好")
elseif score >= 60 then
print("及格")
else
print("不及格")
end
local age = 25
local gender = "male"
if age >= 18 then
if gender == "male" then
print("成年男性")
else
print("成年女性")
end
else
print("未成年人")
end
local i = 1
while i <= 5 do
print(i)
i = i + 1
end
-
local i = 1
repeat
print(i)
i = i + 1
until i > 5
-
-
-
for i = 1, 5 do
print(i)
end
-
-
for i = 5, 1, -1 do
print(i)
end
-
-
for i = 1, 10, 2 do
print(i)
end
-
-
local fruits = {"apple", "banana", "orange"}
for index, value in ipairs(fruits) do
print(index, value)
end
-
-
-
-
local person = {name = "John", age = 30, city = "New York"}
for key, value in pairs(person) do
print(key, value)
end
-
-
-
for i = 1, 10 do
if i == 5 then
break -- 跳出循环
end
print(i)
end
-
:
local i = 1
while i <= 3 do
print(i)
i = i + 1
if i > 3 then
goto end_loop
end
end
:
print("循环结束")
-
-
| 运算符 | 描述 | 示例 |
|---|
+ | 加法 | 1 + 2 = 3 |
- | 减法 | 5 - 3 = 2 |
* | 乘法 | 2 * 3 = 6 |
/ | 除法 | 10 / 2 = 5 |
^ | 幂运算 | 2 ^ 3 = 8 |
% | 取模 | 10 % 3 = 1 |
- | 负号 | -5 |
| 运算符 | 描述 | 示例 |
|---|
== | 等于 | 1 == 1 → “ |
~= | 不等于 | 1 ~= 2 → “ |
< | 小于 | 1 < 2 → “ |
> | 大于 | 2 > 1 → “ |
<= | 小于等于 | 1 <= 1 → “ |
>= | 大于等于 | 2 >= 1 → “ |
| 运算符 | 描述 | 示例 |
|---|
and | 逻辑与 | and false → false |
or | 逻辑或 | or false → “ |
not | 逻辑非 | not → false |
注意: 0 和 "" (空字符串) 在 Lua 中都视为 True。只有 false 和 nil 为假。
-
print(nil and "hello") -- nil
print(false and "hello") -- false
print("hello" and "world") -- world
-
print(nil or "hello") -- hello
print(false or "hello") -- hello
print("hello" or "world") -- hello
-
local name = input_name or "Guest"
| 运算符 | 描述 | 示例 |
|---|
.. | 字符串连接 | "Hello" .. " Lua" → "Hello Lua" |
local str1 = "Hello"
local str2 = "Lua"
local result = str1 .. " " .. str2
print(result) -- Hello Lua
| 运算符 | 描述 | 示例 |
|---|
. | 点运算符 | person.name |
[] | 方括号运算符 | person["name"] |
local person = {name = "John", age = 30}
print(person.name) -- John
print(person["age"]) -- 30
local key = "name"
print(person[key]) -- John
-
local module = {}
-
local private_var = "private"
-
function module.public_function()
-- 函数体
end
-
local function private_function()
-- 函数体
end
-
return module
-
local math = require("math")
-
app_VERSION = "1.0.0"
-
function main()
print("Hello, Lua!")
-- 程序逻辑
end
-
if arg and arg[0] == debug.getinfo(1, "S").source:sub(2) then
main()
end
-
error("发生错误")
-
if not value then
error("值不能为空")
end
-
local success, result = pcall(function()
return 10 / 0
end)
if success then
print("成功:", result)
else
print("错误:", result)
end
-
local function error_handler(err)
return "错误处理: " .. err
end
local success, result = xpcall(function()
return 10 / 0
end, error_handler)
print(success, result)
- 缩进: 使用 4 个空格或 1 个制表符
- 命名规范:
- 变量名: 小写字母,单词间用下划线分隔 (
local user_name)
- 函数名: 小写字母,单词间用下划线分隔 (
function calculate_total())
- 常量: 大写字母,单词间用下划线分隔 (
local MAX_SIZE = 100)
- 模块名: 小写字母,单词间用下划线分隔 (
local utils = require("utils"))
- 代码组织:
- 相关代码放在一起
- 使用空行分隔不同逻辑块
- 函数不要过长,保持单一职责
local print = print
local math = math
local table = table
- 避免全局变量:
- 全局变量访问速度较慢
- 容易造成命名冲突
- 字符串连接:
- 对于大量字符串连接,使用
table.concat
local parts = {}
for i = 1, 1000 do
parts[#parts + 1] = tostring(i)
end
local result = table.concat(parts, ", ")
- 变量作用域:
- 忘记使用
local 关键字,导致变量泄漏到全局作用域
- 局部变量在块结束后不可访问
- 类型判断:
- Lua 是动态类型语言,注意类型检查
- 使用
type() 函数检查变量类型
- 表索引:
- Lua 表索引从 1 开始,不是 0
- 避免使用 nil 作为表索引
- 逻辑判断:
- 只有
false 和 nil 为假,其他值都为真
- 空字符串
"" 和数字 0 都是真
-
-
function celsius_to_fahrenheit(celsius)
return (celsius * 9/5) + 32
end
-
function fahrenheit_to_celsius(fahrenheit)
return (fahrenheit - 32) * 5/9
end
-
local c = 25
local f = celsius_to_fahrenheit(c)
print(c .. "°C = " .. f .. "°F")
f = 77
c = fahrenheit_to_celsius(f)
print(f .. "°F = " .. c .. "°C")
-
-
function factorial(n)
if n == 0 or n == 1 then
return 1
else
return n * factorial(n - 1)
end
end
-
for i = 0, 10 do
print(i .. "! = " .. factorial(i))
end
-
-
function fibonacci(n)
if n == 0 then
return 0
elseif n == 1 then
return 1
else
return fibonacci(n - 1) + fibonacci(n - 2)
end
end
-
function fibonacci_iterative(n)
if n == 0 then
return 0
elseif n == 1 then
return 1
end
local a, b = 0, 1
for i = 2, n do
a, b = b, a + b
end
return b
end
-
print("递归方法:")
for i = 0, 10 do
print("fib(" .. i .. ") = " .. fibonacci(i))
end
print("迭代方法:")
for i = 0, 10 do
print("fib(" .. i .. ") = " .. fibonacci_iterative(i))
end
- 2026-04-05: 拆分并细化 Lua 基础语法细节。
- 2026-04-05: 扩写内容,增加详细的变量、注释、控制流、运算符、程序结构、错误处理、最佳实践和代码示例等内容。