Reputation: 3405
local a = {1,2,3,4}
print(pcall(#a[1])) -- still error
Should pcall()
return false
if error and true
if all good?How do I handle errors?
Upvotes: 6
Views: 26687
Reputation: 97
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
Upvotes: 4
Reputation: 3405
-- 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.
Upvotes: 15