how to retrieve variable arguments in lua 5.2 [dup

2019-08-09 17:02发布

问题:

This question already has an answer here:

  • Parameter implicit “arg” in functions not work in Lua 1 answer

The reference pages all say things like

function this(...)
end

However when I try to apply the supposed arg variable all I get is a nil reference. Any attempt I've made to capture the arguments results in a nil table. I've tried forcing a local tab = {...} and still get the nil reference. The closest I've managed to get to capturing the arguments is a select("#",...) which only returns the number of arguments. Whenever I try to capture this outside parameter declaration I get nothing but another error...

I've been thoroughly looking into this with no avail... any way I can accomplish this without forcibly passing a table?

回答1:

The arg argument is for Lua 5.0 only. Since Lua 5.1, the vararg expression ... is used instead.

Try this:

function foo(...)
    for k, v in ipairs{...} do
        print(k, v)
    end
end

foo('hello', 'world')


标签: lua