Lua, Error Handling pcall()
11,742
Solution 1
-- 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)
For pcall()
to work, function needs to be passed with out brackets.
Solution 2
The first passed in parameter in pcall is function name, what you have in the example is array, not legal I am afraid
https://www.lua.org/pil/8.4.html
Author by
Srdjan M.
Updated on June 04, 2022Comments
-
Srdjan M. almost 2 years
local a = {1,2,3,4} print(pcall(#a[1])) -- still error
Should
pcall()
returnfalse
if error andtrue
if all good?How do I handle errors?