Log In  


How to reproduce

  • execute code:
print("a")
(nil or print)("b")
  • outputs:
A
runtime error line 1 tab 0
print("a")
attempt to call a number value
at line 1 (tab 0)

note that print("a") is correctly executed regardless of the error being reported on that line!

Workaround

print("a")
local fn=nil or print
fn("b")
3


It is same as print("a")(nil or print)("b").
See https://www.lua.org/manual/5.2/manual.html#3.3

another workaround:

print("a")
;(nil or print)("b")

A semicolon can be used to split ambiguous lines.


ah thanks - was not aware it was a known lua quirks!


Huh, this would have stymied me for an hour or more before I realized what the parser was doing, and why it has to be that way. Good to know.

This might be why C/C++ require you to dereference the function pointer... wait, is there a function reference in C++? I think it would have the same problem parsing similar code.

Oh wait, no, because C/C++ don't allow optional non-delimitation of statements.

But I bet there are other languages that might have the same problem.


@Felice
Not quite on topic, but something I'd rather not leave a misunderstanding on. I'm not aware of any version of C/C++ that requires you to dereference function pointers, at least not the basic pointer-to-function (as opposed to pointer-to-pointer-to-function?). It's recommended if you're not otherwise indicating to readers of your code, but the compiler can tell that a function pointer needs dereferencing based on the type. That said, I've only worked with so many versions, so C89 or original pre-ansi versions might have required it.


@kimiyoribaka
Oops, you're right. I was thinking of the weird way you have to deref method pointers.



[Please log in to post a comment]