I'm using Lua 5.3.
Reading 'Programming in Lua 3rd edition', I came into an exercise asking me to find an f
that makes pcall(pcall, f)
return false
. I think this is equivalent to make pcall(f)
raise an error. But seems use pcall
on anything won't do that. For example, let f = nil
and nothing bad happens.
However, I found on the internet that letting f = (function() end)()
does the trick. But I don't understand why. Here f
is just the return value (which is nil
) of the function function() end
right?
Lua Using pcall. Example. pcall stands for "protected call". It is used to add error handling to functions. pcall works similar as try-catch in other languages. The advantage of pcall is that the whole execution of the script is not being interrupted if errors occur in functions called with pcall.
1 - The function for the pcall to run, you can’t call : functions inside a pcall therefore you have to call it with . and now the next arguments are what to pass to the function. 2 - Since you called a : function with . you need to supply what the function belongs to (self) as per OOP rules. 3 - The key of what to Get.
-- 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.
A variety of functions are being called, some of which have no return value @GreenHawk1220 - Even for a function which doesn't return a value, it is absolutely correct in Lua to call it as return yoo (). So, always use return to solve your problem
This does not work
> f = (function() end)()
> pcall(pcall, f)
true false attempt to call a nil value
but this does:
> pcall(pcall,(function() end)())
false bad argument #1 to 'pcall' (value expected)
The difference is that (function() end)()
returns no value, which is different from returning nil
.
Functions written in Lua cannot make this distinction but pcall
is written in C and can make this distinction. (Other examples are print
and type
.)
Note that this behaves as expected (equivalent to the first attempt):
> pcall(pcall,(function() return nil end)())
true false attempt to call a nil value
This is because the code you are calling is equivalent to pcall(pcall)
, not to pcall(pcall, nil)
. The function doesn't return anything; it's adjusted to nil
in some contexts, but is still different from nil
in other contexts (as is the case in this example).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With