赞
踩
当然可以!下面是一份关于 Lua 进阶话题的学习笔记。这份笔记将涵盖 Lua 的一些高级特性,包括元表、协同程序、文件 I/O、错误处理、调试和垃圾回收等。
元表的概念:每个 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"
创建协同程序:
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"
使用 yield
和 resume
:
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"
打开文件:
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()
错误抛出:
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
使用 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)
自动回收:Lua 的垃圾回收是自动的,不需要程序员显式地触发。
手动触发:
collectgarbage()
监控内存使用:
local pagesBefore = collectgarbage("count")
collectgarbage("collect")
local pagesAfter = collectgarbage("count")
print("Memory pages before GC:", pagesBefore)
print("Memory pages after GC:", pagesAfter)
优化垃圾回收:
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
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 中进阶话题的学习笔记。希望这些内容对你有所帮助!如果你有任何问题或需要进一步的解释,请随时提问。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。