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")
P#131500 2023-06-30 19:46

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.

P#131501 2023-06-30 20:19

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

P#131503 2023-06-30 20:20

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.

P#131552 2023-07-02 10:13 ( Edited 2023-07-02 10:21)

@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.

P#131554 2023-07-02 10:29

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

P#131606 2023-07-03 22:44

[Please log in to post a comment]