Deprecated: parse_url(): Passing null to parameter #1 ($url) of type string is deprecated in /www/wwwroot/blog_qqvbc_com/usr/plugins/Access/Access_Core.php on line 339

Deprecated: parse_url(): Passing null to parameter #1 ($url) of type string is deprecated in /www/wwwroot/blog_qqvbc_com/usr/plugins/Access/Access_Core.php on line 392

Deprecated: parse_url(): Passing null to parameter #1 ($url) of type string is deprecated in /www/wwwroot/blog_qqvbc_com/usr/plugins/Access/Access_Core.php on line 394
Lua 进阶极简教程(高阶核心+纯用法) - Joyber 的博客

Lua 进阶极简教程(高阶核心+纯用法)

lua基础版

说明:承接Lua基础教程,全文无冗余描述,仅保留进阶核心知识点 + 作用 + 可运行代码,覆盖Lua高阶开发全部刚需内容。

一、变量深层特性(进阶必懂)

1. 全局环境 \_G

作用:存储所有全局变量、函数的全局表,可动态遍历、修改全局内容

-- 查看所有全局变量
print(_G)

-- 定义全局变量等价写法
_G.testVal = 100
print(testVal)

-- 遍历所有全局函数/变量
for k,v in pairs(_G) do
    print(k,v)
end

2. 局部变量优化

作用:局部变量访问速度远快于全局变量,高阶开发优先局部缓存

-- 缓存全局函数,提升执行效率
local print = print
local pairs = pairs

print("优化后的局部调用")

3. 变量nil清空与垃圾回收

作用:主动置空变量,触发GC释放内存,避免内存泄漏

local data = {1,2,3,4}
data = nil -- 置空引用,等待GC回收
collectgarbage() -- 手动触发垃圾回收

二、函数进阶(Lua核心高阶)

1. 闭包(Closure)

作用:内层函数捕获外层局部变量,变量常驻内存,实现数据私有、状态保存

local function counter()
    local num = 0 -- 被捕获的局部变量
    return function()
        num = num + 1
        return num
    end
end

-- 独立状态,互不干扰
local c1 = counter()
local c2 = counter()
print(c1()) -- 1
print(c1()) -- 2
print(c2()) -- 1

2. 函数尾调用(Tail Call)

作用:尾部调用函数,不堆叠栈帧,避免递归栈溢出,优化递归性能

-- 尾递归写法(无栈溢出)
local function factorial(n, res)
    res = res or 1
    if n <= 1 then return res end
    return factorial(n-1, n*res) -- 纯粹尾部返回
end

print(factorial(10))

3. 函数重载模拟

作用:Lua无原生重载,通过判断参数数量/类型实现多参数适配

local function add(...)
    local args = {...}
    if #args == 1 then
        return args[1] * 2
    elseif #args == 2 then
        return args[1] + args[2]
    end
end

print(add(10))  -- 20
print(add(10,20)) -- 30

4. 函数缓存(记忆化)

作用:缓存函数执行结果,避免重复计算,大幅提升高频函数效率

local cache = {}
local function fib(n)
    if cache[n] then return cache[n] end
    if n <= 2 then return 1 end
    local res = fib(n-1) + fib(n-2)
    cache[n] = res
    return res
end

print(fib(30))

三、Table 高阶操作(Lua灵魂)

1. 数组与哈希表分离原理

作用:Lua table 内部分数组段(连续数字key)、哈希段(自定义key),优化存储

-- 纯数组(高效)
local arr = {1,2,3,4}
-- 纯哈希(高效)
local hash = {a=1,b=2}
-- 混合表(性能略低,不推荐高频使用)
local mix = {1,2,a=3,b=4}

2. 表深拷贝/浅拷贝

作用:解决table默认引用赋值问题,独立复制数据表

-- 浅拷贝(仅复制一层)
local function shallowCopy(t)
    local res = {}
    for k,v in pairs(t) do res[k] = v end
    return res
end

-- 深拷贝(递归复制所有层级)
local function deepCopy(t)
    local res = {}
    if type(t) ~= "table" then return t end
    for k,v in pairs(t) do
        res[k] = deepCopy(v)
    end
    return res
end

local t1 = {1,2,{3,4}}
local t2 = deepCopy(t1)
t2[3][1] = 99
print(t1[3][1]) -- 原表不变

3. 表去重/排序/过滤

作用:高频数组处理工具方法

-- 数组去重
local function unique(arr)
    local temp = {}
    local res = {}
    for _,v in ipairs(arr) do
        if not temp[v] then
            temp[v] = true
            table.insert(res, v)
        end
    end
    return res
end

-- 自定义排序
local arr = {3,1,4,2}
table.sort(arr, function(a,b)
    return a > b -- 降序,默认升序
end)
print(table.concat(arr, ","))

四、元表与元方法(Lua进阶核心)

1. 基础元表读写

作用:为table绑定元表,拦截、自定义table操作行为

local t = {}
local mt = {}

setmetatable(t, mt) -- 绑定元表
local getMt = getmetatable(t) -- 获取元表
print(getMt == mt)

2. 常用元方法全覆盖

作用:拦截加减乘除、取值、赋值、长度、打印等操作

local t = {10,20}
local mt = {
    -- 取值拦截:t[key]
    __index = function(tab, k)
        return "默认值"
    end,
    -- 赋值拦截:t[key] = v
    __newindex = function(tab, k, v)
        print("禁止赋值")
    end,
    -- 加法重载 t1 + t2
    __add = function(a,b)
        return {a[1]+b[1], a[2]+b[2]}
    end,
    -- 打印重载 print(t)
    __tostring = function(tab)
        return "自定义表字符串"
    end,
    -- 长度重载 #t
    __len = function()
        return 99
    end
}

setmetatable(t, mt)
print(t[3])
t[1] = 999
print(t)
print(#t)

3. \_\_index 索引优化(继承核心)

作用:实现表的默认值、数据继承、查找降级

-- 默认值配置
local default = {name="默认", age=18}
local t = {}
setmetatable(t, {__index = default})

print(t.name) -- 找不到key,去元表查找

五、面向对象高阶(纯Lua实现)

1. 标准类、继承、重写

作用:完整OOP体系,支持封装、单继承、方法重写

-- 父类
local Person = {}
Person.__index = Person

function Person:new(name, age)
    local self = setmetatable({}, Person)
    self.name = name
    self.age = age
    return self
end

function Person:show()
    print(self.name, self.age)
end

-- 子类继承
local Student = {}
Student.__index = Student
setmetatable(Student, Person) -- 继承父类

function Student:new(name, age, id)
    local self = Person:new(name, age)
    self.id = id
    return setmetatable(self, Student)
end

-- 方法重写
function Student:show()
    print("学生:", self.name, self.id)
end

local s = Student:new("张三", 16, "001")
s:show()

2. 私有变量模拟

作用:通过闭包实现类私有属性,外部无法修改

local function User(name)
    -- 私有变量
    local _name = name

    -- 公开方法
    return {
        getName = function()
            return _name
        end,
        setName = function(n)
            _name = n
        end
    }
end

local u = User("李四")
print(u.getName())
-- print(u._name) 无法访问私有变量

六、协程高阶(Lua特色)

1. 协程完整生命周期

作用:掌握协程创建、启动、暂停、恢复、状态判断

local co = coroutine.create(function()
    print("协程第一步")
    coroutine.yield("暂停返回值")
    print("协程第二步")
    return "结束返回值"
end)

print(coroutine.status(co)) -- suspended 挂起
local ok, res1 = coroutine.resume(co)
print(res1)
local ok2, res2 = coroutine.resume(co)
print(res2)
print(coroutine.status(co)) -- dead 结束

2. 协程传参技巧

作用:resume与yield双向传参,实现数据交互

local co = coroutine.create(function(a)
    print("初始参数:", a)
    local b = coroutine.yield("第一次返回")
    print("恢复参数:", b)
end)

coroutine.resume(co, 100)
coroutine.resume(co, 200)

七、模块化与代码解耦

1. 标准模块封装写法

作用:规范模块导出,隔离全局环境,工程化开发必备

-- 新建 tool.lua 模块文件
local Tool = {}
Tool.__index = Tool

-- 私有函数(外部无法访问)
local function log(str)
    print("[日志]", str)
end

-- 公开函数
function Tool:add(a,b)
    log("执行加法")
    return a + b
end

return Tool

-- 主文件调用
-- local Tool = require("tool")
-- print(Tool:add(1,2))

2. 模块卸载与重载

作用:解决require缓存问题,支持热更新

-- 卸载模块
package.loaded["tool"] = nil
-- 重新加载
local Tool = require("tool")

八、错误处理与调试高阶

1. assert 断言

作用:条件不成立直接报错,用于参数校验

local num = nil
assert(num, "变量不能为空!")

2. xpcall 带栈追踪捕获错误

作用:比pcall多堆栈信息,精准定位报错位置

local function errHandler(err)
    return err .. "\n" .. debug.traceback()
end

local ok, res = xpcall(function()
    print(1/0)
end, errHandler)

if not ok then
    print("错误详情:", res)
end

3. debug 调试库

作用:查看函数栈、局部变量,高阶调试排错

local function test()
    local a = 100
    print(debug.localvars(1)) -- 打印当前函数局部变量
end
test()

九、字符串与正则进阶

作用:Lua原生正则(模式匹配),无需第三方库

local s = "Lua123Python456"

-- 匹配数字
print(string.match(s, "%d+"))
-- 匹配字母
print(string.match(s, "%a+"))
-- 全局替换
print(string.gsub(s, "%d", ""))
-- 查找所有匹配
for v in string.gmatch(s, "%d+") do
    print(v)
end

十、GC内存优化(工程必备)

作用:控制垃圾回收,优化游戏/长驻程序内存

collectgarbage("stop")  -- 停止GC
collectgarbage("restart")-- 重启GC
collectgarbage("count") -- 获取当前内存占用(KB)
collectgarbage()        -- 手动全量回收

print("当前内存:", collectgarbage("count"))

标签: none

添加新评论