error指定错误等级

本文详细探讨了Lua编程中error函数用于抛出错误的机制,并深入解析了pcall函数如何捕获和处理这些错误,通过实例脚本pcall_3.lua阐述了这两者在实际编程中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值