lua代码及解释
脚本名称:pcall_3.lua
--[[
error:
两个参数,第一个参数是错误信息,第二个参数是错误级别
默认级别为1
0:表示不显示错误出现位置
1:表示error函数调用的位置
2:调用error函数的函数的位置
3:依次类推
]]
function fun(str)
if type(str) ~= "string" then
error("string expected")
else
return str
end
end
local ok, err = pcall(fun, {x = 1})
if not ok then
print(err)
end
--运行结果:pcall_3.lua:15: string expected
function fun0(str)
if type(str) ~= "string" then
error("string expected", 0)
else
return str
end
end
local ok, err = pcall(fun0, {x = 1})
if not ok then
print(err)
end
--运行结果:string expected
function fun1(str)
if type(str) ~= "string" then
error("string expected", 1)
else
return str
end
end
local ok, err = pcall(fun1, {x = 1})
if not ok then
print(err)
end
--运行结果:pcall_3.lua:45: string expected
function fun2(str)
if type(str) ~= "string" then
error("string expected", 2)
else
return str
end
end
function foo()
local ok, err = fun2({x = 1})
return ok, err
end
local ok, err = pcall(foo)
if not ok then
print(err)
end
--运行结果:pcall_3.lua:67: string expected
function fun3(str)
if type(str) ~= "string" then
error("string expected", 3)
else
return str
end
end
function bar()
local ok, err = fun3({x = 1})
return ok, err
end
local ok, err = bar()--pcall(bar)
if not ok then
print(err)
end
--运行结果:string expected
local ok, err = pcall(fun3, {x = 1})
if not ok then
print(err)
end
--运行结果:pcall_3.lua:98: string expected