Lua 编程语言的全面基础语法总结

在这里插入图片描述


以下是 Lua 编程语言的全面基础语法总结,涵盖核心概念和常用语法结构:



一、注释

-- 单行注释

--[[
多行注释
可以跨越多行
]]

二、变量与数据类型

1. 变量声明

local a = 10                -- 局部变量
b = "Hello Lua"             -- 全局变量(默认全局)

2. 数据类型

• nil:空值或未定义
• boolean:truefalse
• number:整数或浮点数(Lua 5.3+ 支持整数类型)
• string:字符串(可用单引号 ' 或双引号 "
• table:唯一的数据结构,用于数组、字典、对象等
• function:函数(一等公民)
• userdata:C 扩展数据
• thread:协程(coroutine)

3. 字符串操作

local s = "Hello"
print(s .. " World")       -- 字符串拼接
print(#s)                  -- 字符串长度(#运算符)
print(s:upper())           -- 方法调用(等价于 string.upper(s))

三、运算符

类型运算符示例
算术+, -, *, /, %, ^a = 5 + 3
比较==, ~=, >, <, >=, <=if a == b then
逻辑and, or, notif a and b then
字符串连接..print("a".."b")
长度##table

四、流程控制

1. 条件语句

if condition then
    -- 代码块
elseif condition2 then
    -- 代码块
else
    -- 代码块
end

2. 循环

-- while 循环
while condition do
    -- 代码块
end

-- for 数值循环
for i = 1, 10 do        -- 包含1和10
    print(i)
end

-- for 泛型循环(遍历表)
local t = {a=1, b=2}
for key, value in pairs(t) do
    print(key, value)
end

-- repeat-until 循环
repeat
    -- 代码块
until condition

五、函数

1. 定义函数

function add(a, b)
    return a + b
end

-- 匿名函数
local square = function(x)
    return x * x
end

-- 多返回值
function divide(a, b)
    return math.floor(a / b), a % b
end

2. 可变参数

function sum(...)
    local total = 0
    for _, v in ipairs({...}) do
        total = total + v
    end
    return total
end

六、表(Table)

1. 创建表

local t1 = {}               -- 空表
local t2 = {1, 2, 3}        -- 数组形式
local t3 = {name="Alice", age=30} -- 键值对

2. 表操作

t = {1, 2, 3}
t[4] = 4                   -- 添加元素
t["name"] = "Bob"          -- 字符串键
table.insert(t, 5)         -- 在末尾插入
table.remove(t, 2)         -- 删除第2个元素
table.sort(t)              -- 排序

3. 元表(Metatable)与元方法

local mt = {
    __index = function(t, k)
        return k * 2       -- 当访问不存在的键时触发
    end
}

local t = setmetatable({}, mt)
print(t[3])                -- 输出 6(3*2)

七、模块与包管理

1. 创建模块

-- mymodule.lua
local M = {}

function M.add(a, b)
    return a + b
end

return M

2. 使用模块

local mymodule = require("mymodule")
print(mymodule.add(2, 3))  -- 输出 5

八、错误处理

-- 捕获错误
local success, result = pcall(function()
    -- 可能出错的代码
    error("Something wrong!")
end)

if success then
    print("Success:", result)
else
    print("Error:", result)
end

九、协程(Coroutine)

local co = coroutine.create(function()
    print("Coroutine started")
    coroutine.yield()       -- 挂起协程
    print("Coroutine resumed")
end)

coroutine.resume(co)        -- 启动协程
coroutine.resume(co)        -- 恢复执行

十、其他特性

• 弱引用表:通过 setmetatable(t, {__mode="v"}) 实现垃圾回收优化。
• 短路求值:andor 支持短路逻辑。
• 简写语法:a = a or b(等价于三元运算符)。


十一、示例代码综合

-- 函数返回多个值
function minmax(a, b)
    return a < b and a or b, a < b and b or a
end

local min, max = minmax(3, 5)
print(min, max)  -- 输出 3 5

-- 表遍历
local t = {x=1, y=2, z=3}
for k, v in pairs(t) do
    print(k, v)
end

Lua 语法简洁灵活,适合嵌入式开发、游戏脚本等领域。掌握以上基础后,可以进一步学习 Lua 的元编程、面向对象模式等高级特性。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

独隅

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值