Lua笔记6 编译、执行与错误

1. 编译

dofile() 

运行时编译:

loadfile()
loadstring(string)()  返回一个函数,并执行
例: loadstring("print('hello world')")();      
例2:i=100; local i=32; loadstring("print(i)");  ==> 100     // 在全局环境中编译,因此会引用全局的变量

调用c代码:

package.loadlib(path, functionName)


2. 错误处理

assert(1 > 2, "erroooooor");
error("bug...")
function errorFunction(args) if args == nil then error("params needed.") else print("ok.") end end
local status, err = pcall(errorFunction, nil) ==> false // errorfunction 中的错误不会传递

使用技巧:
if (pcall(function()
-- code
end)) then
-- code
else
-- error handle
end
function errorFunction(args) 
if args == nil then
error({msg = "params needed.", code=121}) -- error信息
else
print("ok.")
end
end
function errorHandler(err)
print(err.code) -- error code
print(debug.traceback()) -- 调用栈信息
end

xpcall(errorFunction, errorHandler) -- 错误不会传递








原文地址:https://www.cnblogs.com/lavieenrose/p/2330744.html