当前位置:   article > 正文

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

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

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

Lua 进阶学习笔记

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

  • 设置元表

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

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

    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"
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
2. 协同程序 (Coroutines)
  • 创建协同程序

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

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

    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"
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
  • 使用 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"
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
3. 文件 I/O
  • 打开文件

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

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

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

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

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

    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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
  • 错误恢复

    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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
5. 调试
  • 使用 assert 函数

    local x = 10
    assert(x > 0, "x must be positive")
    
    • 1
    • 2
  • 使用 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()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
  • 使用 print 函数

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

  • 手动触发

    collectgarbage()
    
    • 1
  • 监控内存使用

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

    • 减少全局变量
    • 使用弱表
    • 避免大对象
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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
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()
  • 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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/963952
推荐阅读
相关标签
  

闽ICP备14008679号