Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error with self invoking anonymous functions in Lua

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?

like image 814
Keith Bennett Avatar asked Sep 06 '26 02:09

Keith Bennett


1 Answers

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.

like image 186
Joseph Sible-Reinstate Monica Avatar answered Sep 08 '26 09:09

Joseph Sible-Reinstate Monica



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!