Lua 基础入门


第1节:基础概念

注释

-- 单行注释
 
--[[
 多行注释
 可以写很多行
--]]

语句

Lua 中语句可以用分号分隔,但分号通常是可选的

print("hello")
print("world") -- 不需要分号
 
a = 1; b = 2; c = 3 -- 同一行多条语句时才需要分号

第2节:变量与数据类型

命名规则

  • 由字母、数字、下划线组成
  • 不能以数字开头
  • 区分大小写(nameName 不同)
  • 避免使用关键字(如 if, then, end 等)
  • 惯例:常量用全大写 MAX_SIZE,变量用小写+下划线 user_name

声明变量

-- Lua 中变量默认是全局的
x = 10 -- 全局变量(不推荐)
 
-- 使用 local 声明局部变量(强烈推荐)
local name = "Alice"
local age = 25
local is_admin = true
 
-- 多重赋值
local a, b, c = 1, 2, 3 -- a=1, b=2, c=3
local x, y = y, x -- 交换变量(无需临时变量)
 
-- 变量个数不匹配时
local a, b = 1, 2, 3 -- a=1, b=2, 3 被丢弃
local a, b, c = 1, 2 -- a=1, b=2, c=nil

nil

nil 表示”无”或”不存在”。未被赋值的变量默认值为 nil,删除变量也赋予 nil

local t = {1, 2, 3}
t[2] = nil -- 删除表中元素
print(#t) -- 3 → 2(但要注意 nil 在表中的行为)

8 种基本类型一览

类型说明示例
nil空值,表示无nil
boolean布尔值true, false
number数字(整数和浮点)42, 3.14, 0xFF
string字符串"hello", 'world'
function函数function() end
userdata用户数据(C传递)io.stdin
thread协程coroutine.create(...)
table表(唯一数据结构){1, 2, 3}, {a=1}
-- type() 函数返回类型字符串
print(type(42)) --> number
print(type("hello")) --> string
print(type(nil)) --> nil
print(type({})) --> table
print(type(print)) --> function

第3节:数字与字符串

数字 (Number)

在 Lua 5.3+ 中,数字分整数浮点数两种子类型,内部自动转换:

local int = 42
local float = 3.14
local hex = 0xFF -- 十六进制 = 255
local exp = 1.5e3 -- 科学计数法 = 1500
 
-- 数学运算
local a = 10 + 3 -- 13
local b = 10 - 3 -- 7
local c = 10 * 3 -- 30
local d = 10 / 3 -- 3.333...(Lua 除法的结果始终是浮点数)
local e = 10 // 3 -- 3(整除,Lua 5.3+)
local f = 10 % 3 -- 1(取模)
local g = 10 ^ 3 -- 1000(幂运算)
 
-- 类型转换
print(math.tointeger(3.0)) -- 3
print(tostring(42)) -- "42"
print(tonumber("123")) -- 123
print(tonumber("abc")) -- nil(转换失败返回 nil)
 
-- 数学库
print(math.pi) -- 3.1415926535898
print(math.abs(-10)) -- 10
print(math.max(1, 5, 3)) -- 5
print(math.sin(0)) -- 0.0
print(math.random(1, 100)) -- 1~100 之间的随机整数
math.randomseed(os.time()) -- 设置随机种子(程序开头调用一次)

字符串 (String)

-- 字符串表示方式
local s1 = "hello"
local s2 = 'world'
local s3 = [[
 多行字符串
 可以使用方括号
 无需转义
]]
local s4 = [===[
 带有 = 号的
 多行字符串(可嵌套)
]===]
 
-- 字符串连接:使用 ..
local greeting = "Hello, " .. "Lua!"
print(greeting) -- Hello, Lua!
 
-- 字符串长度
print(#"hello") -- 5
print(string.len("hello")) -- 5
 
-- 大小写转换
print(string.upper("hello")) -- HELLO
print(string.lower("WORLD")) -- world
 
-- 字符串查找
local str = "Hello Lua World"
print(string.find(str, "Lua")) -- 7 9(起始和结束位置)
print(string.match(str, "Lua")) -- Lua(返回匹配内容)
print(string.gsub(str, "Lua", "Lua!")) -- Hello Lua! World 2(替换次数)
 
-- 字符串分割与格式化
local date = "2024-01-15"
local year, month, day = string.match(date, "(%d+)-(%d+)-(%d+)")
print(year, month, day) -- 2024 01 15
 
local formatted = string.format("Name: %s, Age: %d", "Alice", 25)
print(formatted) -- Name: Alice, Age: 25
 
print(string.rep("Ab", 3)) -- AbAbAb(重复)
print(string.sub("Hello", 2, 4)) -- ell(子串)

字符串方法调用(冒号语法)

local s = "lua"
-- 以下两种写法等价
print(string.upper(s)) -- 函数式调用
print(s:upper()) -- 方法式调用(推荐)

第4节:表 (Table) 基础

表是 Lua 唯一的数据结构,可充当数组、字典、集合、对象等。

数组形式

-- 创建数组(索引从 1 开始!)
local arr = {10, 20, 30, 40, 50}
print(arr[1]) -- 10(注意:Lua 索引从 1 开始)
print(arr[4]) -- 40
print(#arr) -- 5(获取数组长度)
 
-- 数组操作
table.insert(arr, 60) -- 末尾插入 → {10,20,30,40,50,60}
table.insert(arr, 2, 15) -- 指定位置插入 → {10,15,20,30,40,50,60}
table.remove(arr, 2) -- 移除索引2 → {10,20,30,40,50,60}
table.remove(arr) -- 移除末尾 → {10,20,30,40,50}
 
-- 遍历数组
for i, v in ipairs(arr) do
 print(i, v)
end

字典(键值对)形式

local person = {
 name = "Bob",
 age = 30,
 city = "Beijing",
 ["favorite-lang"] = "Lua", -- 键有特殊字符时用 ["key"]
}
 
print(person.name) -- Bob
print(person["name"]) -- Bob(等价写法)
print(person["favorite-lang"]) -- Lua
 
-- 添加/修改
person.email = "bob@example.com"
person.age = 31
 
-- 删除
person.city = nil
 
-- 遍历字典
for k, v in pairs(person) do
 print(k, v)
end

混合使用

local mixed = {
 10, 20, 30, -- 数组部分 [1]=10, [2]=20, [3]=30
 name = "test", -- 哈希部分
 [100] = "one hundred", -- 哈希部分
}
print(mixed[1]) -- 10
print(mixed.name) -- test
print(mixed[100]) -- one hundred

表操作常用函数

local t = {3, 1, 4, 1, 5}
table.sort(t) -- {1, 1, 3, 4, 5}
table.concat(t, ", ") -- "1, 1, 3, 4, 5"
 
-- 自定义排序
local students = {
 {name = "Alice", score = 90},
 {name = "Bob", score = 85},
 {name = "Charlie", score = 95},
}
table.sort(students, function(a, b) return a.score > b.score end)

第5节:运算符

算术运算符

运算符说明示例结果
+5 + 38
-5 - 32
*5 * 315
/5 / 22.5
//整除5 // 22
^5 ^ 225
%取模5 % 21

关系运算符

运算符说明
==等于
~=不等于
<小于
>大于
<=小于等于
>=大于等于
print(5 == 5) -- true
print(5 ~= 3) -- true
print("abc" < "abd") -- true(字符串按字典序比较)
print({} == {}) -- false(表比较的是引用,不是内容)

逻辑运算符

运算符说明
and
or
not
-- Lua 中只有 nil 和 false 被视为"假",其他都为"真"(包括 0 和空字符串)
print(0 and 1) -- 1(0 是真值!)
print(nil and 10) -- nil
print(nil or "default") -- "default"(常用于设置默认值)
print(not true) -- false
 
-- 短路求值:三元运算符的替代写法
local score = 85
local result = (score >= 60) and "pass" or "fail" -- "pass"

拼接运算符

local a = "Hello"
local b = "World"
print(a .. " " .. b) -- Hello World

长度运算符

print(#"hello") -- 5
print(#{1,2,3,4}) -- 4

运算符优先级

从高到低:

^
not # - (一元负号)
* / // %
+ -
..
< > <= >= ~= ==
and
or

第6节:控制流

if 语句

local score = 85
 
if score >= 90 then
 print("A")
elseif score >= 80 then
 print("B")
elseif score >= 70 then
 print("C")
elseif score >= 60 then
 print("D")
else
 print("F")
end
 
-- 单行写法
if score > 60 then print("pass") end

while 循环

local i = 1
while i <= 5 do
 print(i)
 i = i + 1
end

repeat-until 循环(类似 do-while)

至少执行一次,直到条件为真时结束:

local i = 1
repeat
 print(i)
 i = i + 1
until i > 5

for 循环 — 数值型

-- 基本形式:for var = start, end [, step] do ... end
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
 
-- for 循环中的变量是局部的,循环后不可访问

for 循环 — 泛型(迭代器)

local arr = {"a", "b", "c"}
 
-- ipairs:顺序遍历数组(索引从1开始,遇到nil停止)
for i, v in ipairs(arr) do
 print(i, v)
end
 
-- pairs:遍历表中所有键值对(包含哈希部分)
local info = {name = "Tom", age = 20}
for k, v in pairs(info) do
 print(k, v)
end

break 语句

Lua 中只有 break没有 continue

for i = 1, 10 do
 if i == 5 then
 break -- 跳出循环
 end
 print(i)
end
-- 输出:1 2 3 4
 
-- 模拟 continue(Lua 5.2+ 支持 goto)
for i = 1, 10 do
 if i % 2 == 0 then
 goto continue
 end
 print(i) -- 只打印奇数
 ::continue::
end

第7节:函数

函数定义

-- 基本定义
function greet(name)
 print("Hello, " .. name)
end
 
greet("World") -- Hello, World
 
-- 多返回值
function getMinMax(arr)
 local min = arr[1]
 local max = arr[1]
 for _, v in ipairs(arr) do
 if v < min then min = v end
 if v > max then max = v end
 end
 return min, max
end
 
local a, b = getMinMax({5, 3, 9, 1, 7})
print(a, b) -- 1 9

函数作为一等公民

-- 函数可以赋给变量
local f = function(x) return x * 2 end
print(f(5)) -- 10
 
-- 函数可以作为参数
function apply(func, value)
 return func(value)
end
 
local result = apply(function(x) return x + 1 end, 10)
print(result) -- 11
 
-- 函数可以存储在表中
local funcs = {
 add = function(a, b) return a + b end,
 sub = function(a, b) return a - b end,
}
print(funcs.add(3, 5)) -- 8

可变参数 ...

function sum(...)
 local total = 0
 for _, v in ipairs({...}) do
 total = total + v
 end
 return total
end
 
print(sum(1, 2, 3, 4, 5)) -- 15
 
-- select() 函数获取参数
function checkFirst(...)
 print(select(1, ...)) -- 获取第1个参数
 print(select("#", ...)) -- 获取参数总数
end
 
checkFirst("a", "b", "c")
-- 输出: a 3

闭包 (Closure)

function makeCounter()
 local count = 0
 return function()
 count = count + 1
 return count
 end
end
 
local c1 = makeCounter()
print(c1()) -- 1
print(c1()) -- 2
print(c1()) -- 3
 
local c2 = makeCounter()
print(c2()) -- 1(新闭包,独立计数)

递归

-- 阶乘
function factorial(n)
 if n == 0 then return 1 end
 return n * factorial(n - 1)
end
print(factorial(5)) -- 120
 
-- 斐波那契数列
function fib(n)
 if n < 2 then return n end
 return fib(n - 1) + fib(n - 2)
end
print(fib(10)) -- 55

第8节:作用域与块

-- 局部变量作用域限于所在的块(do...end、if、for、函数体等)
local x = 10
 
if true then
 local x = 20 -- 新变量,遮蔽外层的 x
 local y = 30 -- 仅在此 if 块内有效
 print(x) -- 20
end
 
print(x) -- 10
-- print(y) -- nil(y 在此不可见)
 
-- do...end 块:显式创建作用域
do
 local temp = "temporary"
 print(temp) -- temporary
end
-- print(temp) -- nil

第9节:常见标准库速览

字符串库

函数说明
string.len(s)长度
string.upper(s)转大写
string.lower(s)转小写
string.sub(s, i, j)子串
string.find(s, pattern)查找
string.match(s, pattern)匹配
string.gsub(s, pat, repl)替换
string.format(fmt, ...)格式化
string.rep(s, n)重复 n 次

数学库

函数说明
math.abs(x)绝对值
math.ceil(x)向上取整
math.floor(x)向下取整
math.max(...)最大值
math.min(...)最小值
math.random([m, n])随机数
math.sin(x), math.cos(x)三角函数

表库

函数说明
table.insert(t, [pos,] v)插入
table.remove(t [, pos])移除
table.sort(t [, comp])排序
table.concat(t [, sep])拼接字符串
table.move(a1, f, e, t [, a2])移动元素

基础篇总结

恭喜!你已经掌握了 Lua 的核心基础:

  • 变量声明与作用域
  • 8 种数据类型
  • 表(Table)的基础操作
  • 运算符与表达式
  • 条件判断与循环
  • 函数定义与闭包
  • 常用标准库函数

下一步:03-进阶教程.md — 模块、元表、协程、OOP 等高级主题