--编译
--dofile loadfile assert
--dofile 能够编译并执行一个文件 loadfile 只是编译一个文件 assert引发错误,如果它的参数是错误
function dofile(filename)
local f = assert(loadfile(filename))
return f()
end
--loadstring 从一个字符串中读取代码
i = 100
local i = 1
f = loadstring("i = i +1 print(i)")
function g()
i = i+1
print(i)
end
f()
g()
--loadstring 与 一个对应的函数不是完全等价的
--这是因为词法域的问题,loadstring不涉及词法域,而普通函数涉及词法域
--所以loadstring会调用全局变量,而普通函数会调用更为靠近它的局部变量
--程序块的问题,lua中将所有程序块都视为一个匿名函数
--因此可以在程序块中声明局部变量,一个程序块就相当于执行一个具有可变参数的匿名函数
--function(...) a = 1 end
--loadstring("a=1")
--这两个是等价的
f = loadstring("local a = 10; print(a+20)")
f()
--错误 异常 与 追溯
--抛出错误 if not condition then XXX end
n = io.read("*number")
if not n then error("invalid input") end
--assert函数抛出错误
--assert两个参数,第一个为true就返回该参数,否则返回第二个参数
n = assert(io.read("*number"),"input error")
--file = assert(io.open(name,"read")) --读取文件看是否产生错误
--处理错误 抛出错误的函数+pcall函数实现
function foo()
n = io.read("*number")
if not n then error("input error") end
end
if pcall(foo) then --没有出错
else --n的输入出错就把n置为1 并且打印换行后再打印n
n = 1
print("\n"..n)
end
--追溯错误消息 打印pcall的返回值
print(pcall(foo))
--返回错误的层级
function foo(str)
if type(str) ~= "string" then
error("string expected",2)
end
end