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