Lua 基础语法教程

本教程基于 basics.lua 文件,详细介绍 Lua 编程语言的基础语法知识。

目录

  1. 变量声明和赋值
  2. 数据类型
  3. 条件语句
  4. 循环结构
  5. 运算符

1. 变量声明和赋值

全局变量

在 Lua 中,不使用 local 关键字声明的变量是全局变量。

1
2
3
-- 全局变量
global_var = 10 -- 不使用local声明的是全局变量
print("Global variable:", global_var)

局部变量

使用 local 关键字声明的变量是局部变量,其作用域仅限于声明它的块。

1
2
3
-- 局部变量
local local_var = 20 -- 使用local声明的是局部变量
print("Local variable:", local_var)

多重赋值

Lua 支持同时给多个变量赋值。

1
2
3
-- 多重赋值
local a, b, c = 1, 2, 3
print("Multiple assignment:", a, b, c)

交换变量值

利用多重赋值的特性,可以方便地交换变量值。

1
2
3
4
5
-- 交换变量值
local x, y = 10, 20
print("Before swap:", x, y)
x, y = y, x
print("After swap:", x, y)

额外示例:变量的默认值

当赋值表达式的数量少于变量数量时,多余的变量会被赋予 nil 值。

1
2
3
-- 变量的默认值
local p, q, r = 1, 2
print("p:", p, "q:", q, "r:", r) -- r 会被赋值为 nil

2. 数据类型

Lua 是一种动态类型语言,共有 8 种基本数据类型:nil、boolean、number、string、table、function、userdata 和 thread。

nil 类型

nil 是一个特殊的值,表示”无”或”不存在”。

1
2
3
-- nil类型
local nil_var = nil
print("nil type:", type(nil_var))

boolean 类型

布尔类型只有两个值:truefalse

1
2
3
4
-- boolean类型
local bool_true = true
local bool_false = false
print("boolean type:", type(bool_true), type(bool_false))

number 类型

Lua 中只有一种数值类型,用于表示整数和浮点数。

1
2
3
4
5
-- number类型(Lua中只有一种数值类型)
local int_num = 42
local float_num = 3.14
local exp_num = 1e-3
print("number type:", type(int_num), type(float_num), type(exp_num))

string 类型

字符串是由零个或多个字符组成的序列,可以用单引号、双引号或长字符串语法([[...]])表示。

1
2
3
4
5
6
7
-- string类型
local str1 = "Hello"
local str2 = 'World'
local str3 = [[Multi-line
string]]
print("string type:", type(str1), str1, str2)
print("Multi-line string:", str3)

table 类型

表是 Lua 中唯一的复合数据类型,可以用来表示数组、字典等数据结构。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
-- table类型(Lua中唯一的复合数据类型)
local tbl = {1, 2, 3}
print("table type:", type(tbl))

-- 表作为数组
local arr = {10, 20, 30, 40, 50}
print("Array elements:")
for i = 1, #arr do
print(i, arr[i])
end

-- 表作为字典
local dict = {name = "John", age = 30, city = "New York"}
print("Dictionary elements:")
for key, value in pairs(dict) do
print(key, value)
end

function 类型

函数是 Lua 中的第一类值,可以存储在变量中、作为参数传递或作为返回值。

1
2
3
4
5
6
7
8
9
10
-- function类型
local func = function() print("Hello") end
print("function type:", type(func))
func() -- 调用函数

-- 命名函数
function greet(name)
print("Hello, " .. name .. "!")
end
greet("Lua")

userdata 和 thread 类型

  • userdata:用于表示由 C 语言创建的自定义类型。
  • thread:用于表示协程(coroutine)。

3. 条件语句

Lua 提供了 ifelseifelse 语句来实现条件判断。

if-else 语句

1
2
3
4
5
6
7
8
9
-- if-else语句
local num = 10
if num > 0 then
print("Positive number")
elseif num < 0 then
print("Negative number")
else
print("Zero")
end

额外示例:嵌套的条件语句

1
2
3
4
5
6
7
8
9
10
11
-- 嵌套的条件语句
local score = 85
if score >= 90 then
print("Excellent!")
elseif score >= 70 then
print("Good job!")
elseif score >= 60 then
print("Pass.")
else
print("Need to improve.")
end

4. 循环结构

Lua 提供了三种循环结构:forwhilerepeat-until

for 循环(数值型)

用于执行固定次数的循环。

1
2
3
4
5
-- for循环(数值型)
print("Numeric for loop:")
for i = 1, 5 do
print(i)
end

for 循环(带步长)

可以指定循环的步长。

1
2
3
4
5
-- for循环(带步长)
print("\nNumeric for loop with step:")
for i = 5, 1, -1 do
print(i)
end

while 循环

在条件为真时重复执行循环体。

1
2
3
4
5
6
7
-- while循环
print("\nWhile loop:")
local count = 1
while count <= 5 do
print(count)
count = count + 1
end

repeat-until 循环

至少执行一次循环体,然后在条件为真时停止。

1
2
3
4
5
6
7
-- repeat-until循环(至少执行一次)
print("\nRepeat-until loop:")
local i = 1
repeat
print(i)
i = i + 1
until i > 5

额外示例:泛型 for 循环

用于遍历表中的元素。

1
2
3
4
5
6
7
8
9
10
11
12
-- 泛型for循环遍历表
print("\nGeneric for loop:")
local fruits = {"apple", "banana", "orange"}
for index, value in ipairs(fruits) do
print(index, value)
end

-- 泛型for循环遍历字典
local person = {name = "Alice", age = 25, job = "Engineer"}
for key, value in pairs(person) do
print(key, value)
end

5. 运算符

算术运算符

1
2
3
4
5
6
7
8
9
-- 算术运算符
local a, b = 10, 3
print("Arithmetic operators:")
print("a + b =", a + b) -- 加法
print("a - b =", a - b) -- 减法
print("a * b =", a * b) -- 乘法
print("a / b =", a / b) -- 除法(浮点数)
print("a % b =", a % b) -- 取模
print("a ^ b =", a ^ b) -- 幂运算

关系运算符

1
2
3
4
5
6
7
8
-- 关系运算符
print("\nRelational operators:")
print("a == b", a == b) -- 等于
print("a ~= b", a ~= b) -- 不等于
print("a > b", a > b) -- 大于
print("a < b", a < b) -- 小于
print("a >= b", a >= b) -- 大于等于
print("a <= b", a <= b) -- 小于等于

逻辑运算符

1
2
3
4
5
6
-- 逻辑运算符
print("\nLogical operators:")
local x, y = true, false
print("x and y", x and y) -- 逻辑与
print("x or y", x or y) -- 逻辑或
print("not x", not x) -- 逻辑非

字符串连接运算符

1
2
3
4
-- 字符串连接运算符
print("\nString concatenation:")
local str1, str2 = "Hello", "World"
print("str1 .. str2 =", str1 .. " " .. str2) -- 使用 .. 连接字符串

额外示例:运算符优先级

Lua 中的运算符优先级从高到低依次为:

  1. ^
  2. 一元运算符(not, #, -)
  3. *, /, %
  4. +, -
  5. ..
  6. <, >, <=, >=, ~=, ==
  7. and
  8. or
1
2
3
4
5
6
-- 运算符优先级示例
local result = 2 + 3 * 4
print("2 + 3 * 4 =", result) -- 结果为 14,因为 * 优先级高于 +

local result2 = (2 + 3) * 4
print("(2 + 3) * 4 =", result2) -- 结果为 20,使用括号改变优先级

运行示例

要运行 basics.lua 文件,只需在命令行中执行:

1
lua basics.lua

运行结果将显示各个部分的输出,包括变量值、数据类型信息、条件判断结果、循环执行过程和运算符计算结果。

总结

本教程介绍了 Lua 编程语言的基础语法,包括:

  • 变量声明和赋值
  • 数据类型
  • 条件语句
  • 循环结构
  • 运算符

通过学习这些基础知识,您已经为进一步学习 Lua 的高级特性(如函数闭包、表操作、模块系统等)打下了坚实的基础。

basics.lua

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
-- Lua基础语法示例
-- print语句使用英语,注释使用中文

-- 1. Variable Declaration and Assignment
print("=== Variable Declaration and Assignment ===")
-- 全局变量
local_var = 10 -- 不使用local声明的是全局变量
print("Global variable:", local_var)

-- 局部变量
local local_var = 20 -- 使用local声明的是局部变量
print("Local variable:", local_var)

-- 多重赋值
local a, b, c = 1, 2, 3
print("Multiple assignment:", a, b, c)

-- 交换变量值
local x, y = 10, 20
a, b = b, a
print("After swap:", a, b)

-- 2. Data Types
print("\n=== Data Types ===")
-- nil类型
local nil_var = nil
print("nil type:", type(nil_var))

-- boolean类型
local bool_true = true
local bool_false = false
print("boolean type:", type(bool_true), type(bool_false))

-- number类型(Lua中只有一种数值类型)
local int_num = 42
local float_num = 3.14
local exp_num = 1e-3
print("number type:", type(int_num), type(float_num), type(exp_num))

-- string类型
local str1 = "Hello"
local str2 = 'World'
local str3 = [[Multi-line
string]]
print("string type:", type(str1), str1, str2)
print("Multi-line string:", str3)

-- table类型(Lua中唯一的复合数据类型)
local tbl = {1, 2, 3}
print("table type:", type(tbl))

-- function类型
local func = function() print("Hello") end
print("function type:", type(func))

-- 3. Conditional Statements
print("\n=== Conditional Statements ===")
local num = 10

-- if-else语句
if num > 0 then
print("Positive number")
elseif num < 0 then
print("Negative number")
else
print("Zero")
end

-- 4. Loop Structures
print("\n=== Loop Structures ===")

-- for循环(数值型)
print("Numeric for loop:")
for i = 1, 5 do
print(i)
end

-- for循环(带步长)
print("\nNumeric for loop with step:")
for i = 5, 1, -1 do
print(i)
end

-- while循环
print("\nWhile loop:")
local count = 1
while count <= 5 do
print(count)
count = count + 1
end

-- repeat-until循环(至少执行一次)
print("\nRepeat-until loop:")
local i = 1
repeat
print(i)
i = i + 1
until i > 5

-- 5. Operators
print("\n=== Operators ===")

-- 算术运算符
local a, b = 10, 3
print("Arithmetic operators:")
print("a + b =", a + b)
print("a - b =", a - b)
print("a * b =", a * b)
print("a / b =", a / b)
print("a % b =", a % b)
print("a ^ b =", a ^ b)

-- 关系运算符
print("\nRelational operators:")
print("a == b", a == b)
print("a ~= b", a ~= b)
print("a > b", a > b)
print("a < b", a < b)
print("a >= b", a >= b)
print("a <= b", a <= b)

-- 逻辑运算符
print("\nLogical operators:")
local x, y = true, false
print("x and y", x and y)
print("x or y", x or y)
print("not x", not x)

-- 字符串连接运算符
print("\nString concatenation:")
local str1, str2 = "Hello", "World"
print("str1 .. str2 =", str1 .. " " .. str2)