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?