编译
- loadstring在编译时不涉及词法域,也就是说,它总在全局环境中编译自己的字符串。当然,可以在字符串中用local显式的指定局部变量。
- loadfile加载编译lua文件,在使用lua文件中的内容前,还需要对lua文件定义,方法如下:f=loadfile("foo.lua"); f();
错误处理
- error抛出异常,如果error被调用,它会将参数作为返回值返回;
- assert第一个参数为假(表达式或函数的返回值为false或nil)时,终止程序;注意,函数默认的返回值是nil,类似void函数,所以用assert调用一个void函数(没有return)会终止程序。
- pcall(func[, func_arg1,...]),第一个参数是被调用函数,之后是该函数的参数。pcall的第一个返回值是pcall的返回值(false:函数抛出异常,true:函数没有抛出异常),之后是被调用函数的返回值;当被调用的函数发生异常时,不会终止程序。
- xpcall(func, debug_func [, func_arg1,...] ),第一个参数是被调用的函数,第二个参数是处理异常的函数(当error被调用时,调用此函数,实参由error返回值提供,也就是error的实参),之后的参数为func函数的参数。
--第8章 编译执行与错误
function loadfileTest()
f = loadfile("5function.lua")
print("-------------after loadfile------------")
f() -- 定义
print("-------------after dingyi--------------")
main()
end
--[[ 此文件不定义main了,以免与loadfile中的main冲突
function main()
loadfileTest()
os.exit()
end]]
function errorTest()
local function _foo(a)
if not a then
error{code=1, msg="arg is nil"}
elseif tostring(type(a)) ~= "number" then
error{code=2, msg="arg is not number"}
elseif a%3==0 then
error{code=3, msg="arg is multiple of 3"}
end
io.write(string.format("OK, number a is %d\n", a))
return true, "OK"
--return false --test assert
end
local res = assert(_foo(31), "test assert") --assert会终止程序
--assert(false, "test boolean")
--pcall中出现错误不会终止程序,第一个是pcall的返回值,之后是被调用函数的返回值
local pcallRes, errorMsg = pcall(_foo, "3")
if not pcallRes then
print(errorMsg.code, errorMsg.msg)
end
print("Test xpcall______________________")
local function debug_(eTable)
print("debug_ is called")
print("table from error to debug_:",eTable.code, eTable.msg)
return {code=-1, msg="xpcall return debug_'s return value"}
end
local xpcallRes, _fooRes1, _fooRes2 = xpcall(_foo, debug_, 6)
if not xpcallRes then
--若res为false,则会调用debug_错误处理函数,并且error会将自己的参数返回,作为调用debug_的实参
print("debug_ has been called")
else
print("_foo results are ", _fooRes1, _fooRes2)
end
os.exit()
end
--loadfileTest()
errorTest()