3

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?

0

1 Answer 1

6

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.

5
  • 1
    It's not an ambiguity. The parser takes the longest valid expression.
    – lhf
    May 26, 2020 at 21:36
  • @lhf Isn't it though? I'd argue that it is an ambiguity, and taking the longest valid expression is how it chooses to resolve the ambiguity. May 26, 2020 at 21:37
  • Also, in Lua 5.1, it really did fail to parse with the error ambiguous syntax (function call x new statement). May 26, 2020 at 21:38
  • Wow! I'm astonished. Do other languages share this behavior? I don't think I've ever seen it before. I decided to place the ";" directly before the function definition (;(function...) to be certain that it would never be considered part of a prior statement. May 27, 2020 at 2:41
  • 2
    Try this in javascript: console.log("test") ( () => console.log("foo"))() same problem, same solution (adding a ;). This happens because parentheses are used for more than one thing in many programming languages, which can lead to these ambiguities. May 27, 2020 at 9:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.