Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua, Error Handling pcall()

Tags:

lua

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?

like image 972
Srdjan M. Avatar asked Jul 12 '26 18:07

Srdjan M.


1 Answers

-- 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.

like image 161
Srdjan M. Avatar answered Jul 18 '26 06:07

Srdjan M.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!