一、初见 Lua:Hello, World!
lua
print("Hello, World!")
如何运行?
对于初学者,最简单的方式是使用在线 Lua 运行环境,你无需在本地安装任何东西。在此推荐使用官网运行
二、核心语法:变量与数据类型
1. 变量声明
Lua 的变量不需要预先声明类型,可以直接赋值。默认情况下,变量是全局的。但最佳实践是使用 local
关键字将其声明为局部变量,以避免污染全局命名空间。
lua
-- 这是一个全局变量 (不推荐)
message = "Hello from a global variable"
-- 这是一个局部变量 (推荐)
local name = "Alice"
local age = 30
print(name, age) -- 可以一次打印多个变量
2. 主要数据类型
Lua 有8种基础数据类型,我们先了解几个最常用的:
- nil : 表示"无"或"空值"。一个未赋值的变量就是
nil
。将一个变量赋值为nil
相当于删除它。 - boolean :
true
或false
。注意,在 Lua 中,只有false
和nil
被视为"假",其他所有值(包括数字0和空字符串"")都是"真"。 - number: 表示所有数字,不区分整数和浮点数(Lua 5.3后可区分)。
- string: 字符串,可以用单引号或双引号表示。
- table : 这是 Lua 最核心、最强大的数据类型!
三、万物之源:table
1. 当作数组使用
当 table
的键是连续的整数时,它就表现得像一个数组。
lua
local fruits = {"apple", "banana", "orange"} -- 这是一个 table
-- 惊奇之处:Lua 的索引是从 1 开始的!
print(fruits[1]) -- 输出: apple
print(fruits[3]) -- 输出: orange
-- 获取长度
print(#fruits) -- 输出: 3
注意!这是一个巨大的不同点! 与大多数编程语言(C, Java, Python, JS)的 0-based 索引不同,Lua 的索引从 1 开始。这是新手最容易犯错的地方。
2. 当作字典(哈希表)使用
你可以用字符串或其他类型的值作为键。
lua
local person = {
name = "Bob",
age = 28,
isStudent = false
}
-- 访问数据
print(person.name) -- 输出: Bob (点表示法)
print(person["age"]) -- 输出: 28 (方括号表示法)
-- 添加新数据
person.city = "New York"
print(person.city) -- 输出: New York
四、流程控制
Lua 的流程控制语法也十分简洁,并以 end
关键字结尾。
1. 条件判断 if-then-else
lua
local score = 85
if score >= 90 then
print("优秀")
elseif score >= 60 then
print("通过")
else
print("不及格")
end
2. 循环
for
循环(数值型):
lua
-- 从 1 循环到 5
for i = 1, 5 do
print(i)
end
for
循环(泛型/迭代器): 这是遍历 table
最常用的方式。ipairs
用于遍历类数组的 table
,pairs
用于遍历类字典的 table
。
lua
-- 遍历数组
local colors = {"red", "green", "blue"}
for index, value in ipairs(colors) do
print(index, value)
end
-- 输出:
-- 1 red
-- 2 green
-- 3 blue
-- 遍历字典
local player_stats = {hp = 100, mp = 50, attack = 15}
for key, value in pairs(player_stats) do
print(key, "is", value)
end
五、函数
函数也是 Lua 中的一等公民,可以像变量一样传递和赋值。
lua
-- 定义一个函数
function greet(name)
return "Hello, " .. name .. "!" -- '..' 是字符串连接符
end
-- 调用函数
local greeting_message = greet("Charlie")
print(greeting_message) -- 输出: Hello, Charlie!
结语
点个赞,关注我获取更多实用 Lua 技术干货!如果觉得有用,记得收藏本文!