Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the use of ... in any expression in a function cause the value of arg to be nil in Lua?

function tell(num,...)
    print("value of implicit table:",arg)
    --print("value of implicit table:",...)
    select(1,arg)
    --select(1,...)
end
tell(12,43,12,55)

Why is it that using ... in an expression causes the value of arg to
be nil e.g. with print("value of implicit table:",...) or select(1,...)?

like image 212
Plakhoy Avatar asked Sep 08 '13 00:09

Plakhoy


1 Answers

Lua 5.1 officially deprecates the use of the arg table for varargs, preferring .... However, there is a compile time option for Lua itself, LUA_COMPAT_VARARG, to permit the use of arg in 5.1 code.

If LUA_COMPAT_VARARG was defined when Lua was compiled, an arg table will be created in varargs functions, and populated with the arguments - unless the compiler detects the use of ... inside the function. In that case, it assumes that you're using 5.1 style varargs instead of 5.0, and doesn't create the table. It does, however, still create the local named arg!

The upshot of this is that if LUA_COMPAT_VARARG is defined, vararg functions that don't use ... in the body get a local arg containing the argument list, and vararg functions that do get a local arg containing nil. This bug is present in all versions of 5.1 and means, in particular, that you can't access a global or upvalue named arg from any varargs functions if LUA_COMPAT_VARARG was defined at compile time.

Lua 5.2 drops support for arg-style varargs entirely and thus does not have this issue regardless of how it was configured at compile time.

(Source: the changes in varargs handling between 5.0 and 5.1, and the LUA_COMPAT_VARARG option, are mentioned in the Lua 5.1 reference manual, section 7.1. The manual refers you to luaconf.h. The exact behaviour is not documented anywhere, as far as I'm aware of; it can be determined experimentally, by reading lparser.c and ldo.c, or from the posts on the mailing list that originally reported this issue.)

like image 166
ToxicFrog Avatar answered Nov 17 '22 12:11

ToxicFrog