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

强颜欢笑 提交于 2020-01-03 08:20:10

问题


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,...)?


回答1:


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



来源:https://stackoverflow.com/questions/18679174/why-does-the-use-of-in-any-expression-in-a-function-cause-the-value-of-arg-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!