I'm trying to use self invoking anonymous functions in Lua, and am seeing some strange behavior.
This:
(function ()
print("self-invoking approach")
end)()
print("standard approach")
works ok and prints the following output:
self-invoking approach
standard approach
but reversing the two:
print("standard approach")
(function ()
print("self-invoking approach")
end)()
results in this error:
➜ hammerspoon lua temp.lua
standard approach
lua: temp.lua:1: attempt to call a nil value
stack traceback:
temp.lua:1: in main chunk
[C]: in ?
Strangely, when code is run in the Lua REPL, the failure only occurs when the function form is second, and both calls are wrapped in an outer function that is called:
function foo()
print("standard approach")
(function ()
print("self-invoking approach")
end)()
end
foo()
What's happening here?
It's a parsing ambiguity. The non-working case is being parsed as:
print("standard approach")(function ()
print("self-invoking approach")
end)()
In other words, it's printing standard approach, then taking the return value of that print (which is nil), and trying to call that with your self-invoking function as the argument (after which it would have tried to call the result of that too, had it not already crashed). To fix it, add a semicolon at the end of the first print function call.
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