Lua 学习笔记之二(进阶话题)

当然可以!下面是一份关于 Lua 进阶话题的学习笔记。这份笔记将涵盖 Lua 的一些高级特性,包括元表、协同程序、文件 I/O、错误处理、调试和垃圾回收等。

Lua 进阶学习笔记

1. 元表 (Metatables)
  • 元表的概念:每个 Lua 表都可以关联一个元表,元表定义了表的行为。

  • 设置元表

    local t = {1, 2, 3}
    local mt = {}  -- 元表
    setmetatable(t, mt)
    
  • 元方法:元表中的特殊方法,例如 __index, __newindex, __metatable, __len, __tostring, __eq 等。

    mt.__index = function(t, key)
        return "Default value for " .. key
    end
    
  • 使用元表

    local t = {}
    local mt = {}
    mt.__index = function(t, key)
        return "Default value for " .. key
    end
    setmetatable(t, mt)
    print(t.x)  -- 输出 "Default value for x"
    
2. 协同程序 (Coroutines)
  • 创建协同程序

    local co = coroutine.create(function()
        print("Hello from coroutine!")
    end)
    
  • 启动协同程序

    coroutine.resume(co)  -- 输出 "Hello from coroutine!"
    
  • 传递值

    local co = coroutine.create(function(x, y)
        local sum = x + y
        print("Sum:", sum)
        return sum
    end)
    
    local result = coroutine.resume(co, 10, 5)
    print("Result:", result)  -- 输出 "Result: 15"
    
  • 使用 yieldresume

    local co = coroutine.create(function()
        print("Coroutine started.")
        local x = coroutine.yield(10)
        print("Received:", x)
        coroutine.yield(20)
        print("Coroutine finished.")
    end)
    
    local status, x = coroutine.resume(co)
    print("Status:", status, "X:", x)  -- 输出 "Status: true X: 10"
    status, x = coroutine.resume(co, "Data")
    print("Status:", status, "X:", x)  -- 输出 "Status: true X: Data"
    status, x = coroutine.resume(co)
    print("Status:", status, "X:", x)  -- 输出 "Coroutine finished." "Status: true X: 20"
    
3. 文件 I/O
  • 打开文件

    local file = io.open("example.txt", "w")
    
  • 写入文件

    file:write("Hello, Lua!\n")
    file:close()
    
  • 读取文件

    local file = io.open("example.txt", "r")
    local content = file:read("*a")  -- 读取整个文件
    print(content)
    file:close()
    
  • 逐行读取文件

    local file = io.open("example.txt", "r")
    for line in file:lines() do
        print(line)
    end
    file:close()
    
4. 错误处理
  • 错误抛出

    function divide(a, b)
        if b == 0 then
            error("Cannot divide by zero")
        end
        return a / b
    end
    
  • 错误捕获

    local function safeDivide(a, b)
        return pcall(function()
            if b == 0 then
                error("Cannot divide by zero")
            end
            return a / b
        end)
    end
    
    local status, result = safeDivide(10, 0)
    if not status then
        print("Error:", result)
    else
        print("Result:", result)
    end
    
  • 错误恢复

    local function divide(a, b)
        if b == 0 then
            error("Cannot divide by zero")
        end
        return a / b
    end
    
    local function errorHandler(err)
        print("Caught error:", err)
    end
    
    local status, result = xpcall(divide, errorHandler, 10, 0)
    if not status then
        print("Error occurred")
    else
        print("Result:", result)
    end
    
5. 调试
  • 使用 assert 函数

    local x = 10
    assert(x > 0, "x must be positive")
    
  • 使用 debug

    local function debugPrint(level)
        local info = debug.getinfo(2, "Sl")
        print("Function name:", info.short_src .. ":" .. info.currentline)
        print("Local variables:")
        for i = 1, level do
            local name, value = debug.getlocal(level, i)
            print("  ", name, "=", value)
        end
    end
    
    local function foo()
        local x = 10
        local y = 20
        debugPrint(1)
    end
    
    foo()
    
  • 使用 print 函数

    local x = 10
    print("x =", x)
    
6. 垃圾回收
  • 自动回收:Lua 的垃圾回收是自动的,不需要程序员显式地触发。

  • 手动触发

    collectgarbage()
    
  • 监控内存使用

    local pagesBefore = collectgarbage("count")
    collectgarbage("collect")
    local pagesAfter = collectgarbage("count")
    
    print("Memory pages before GC:", pagesBefore)
    print("Memory pages after GC:", pagesAfter)
    
  • 优化垃圾回收

    • 减少全局变量
    • 使用弱表
    • 避免大对象
7. 示例:使用元表实现简单的键值存储
local KeyValueStore = {}
local mt = {}

mt.__index = function(t, key)
    return t[key] or nil
end

mt.__newindex = function(t, key, value)
    t[key] = value
end

KeyValueStore.new = function()
    local store = setmetatable({}, mt)
    return store
end

local store = KeyValueStore.new()
store["name"] = "Alice"
store["age"] = 25

print(store["name"])  -- 输出 "Alice"
print(store["age"])  -- 输出 25
8. 示例:使用协同程序实现简单的任务调度
local TaskScheduler = {}
TaskScheduler.__index = TaskScheduler

function TaskScheduler:new()
    local scheduler = setmetatable({
        tasks = {},
        current = nil
    }, TaskScheduler)
    return scheduler
end

function TaskScheduler:add(task)
    table.insert(self.tasks, task)
end

function TaskScheduler:run()
    while #self.tasks > 0 do
        local task = self.tasks[1]
        table.remove(self.tasks, 1)
        self.current = task
        coroutine.resume(task)
        self.current = nil
    end
end

function TaskScheduler:yield()
    if self.current then
        coroutine.yield()
    end
end

local scheduler = TaskScheduler:new()

local task1 = coroutine.create(function()
    print("Task 1: Started.")
    scheduler:yield()
    print("Task 1: Finished.")
end)

local task2 = coroutine.create(function()
    print("Task 2: Started.")
    scheduler:yield()
    print("Task 2: Finished.")
end)

scheduler:add(task1)
scheduler:add(task2)
scheduler:run()

这些是在 Lua 中进阶话题的学习笔记。希望这些内容对你有所帮助!如果你有任何问题或需要进一步的解释,请随时提问。

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值