local a = {1,2,3,4}
print(pcall(#a[1])) -- still error
如果有错误并且一切正常,应该pcall()
返回。如何处理错误?false
true
-- Example 1.
a = {1,2,3,4}
function check()
return #a[1]
end
print(pcall(check)) -- false | attempt to get length of field '?' (a number value)
local v, massage = pcall(check)
print(v, massage) -- "v" contains false or true, "massage" contains error string
-- Example 2.
-- Passing function and parameter...
function f(v)
return v + 2
end
a, b = pcall(f, 1)
print(a, b) --> true | 3
a, b = pcall(f, "a")
print(a, b) -- false | attempt to perform arithmetic on local 'v' (a string value)
为了pcall()
正常工作,必须在不带括号的情况下传递功能。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句