array as parameter list lua

2019-06-23 19:35发布

问题:

Today i was working some with lua,with that "oldesh" for me language,and did find what you can get arguments as array,like soo:

function foo(someting,...)
    local arrayofargs = arg
    -- code here
end

And now,i'm intresting.Can that be in "other way"? Can you pass array,not as array,but like param list,Like so:

function bar(a1,a2)
    print(a1+a1)
end

function foo(someting,...)
    local arrayofargs = arg
    bar(arg)
end

Yes,you cant do that.But can i somehome make someting like that?

回答1:

If you're talking about the fact that old versions of Lua gave an automatic arg containing all args received by a vararg function, then you can just do local arg={...} right at the beginning of the function.

If you want to convert an array into a list, use table.unpack.

So, your example would be

function foo(someting,...)
    local arg={...}
    bar(table.unpack(arg))
end

but this does not make much sense, since you can just do this, which is clearer and simpler:

function foo(someting,...)
    bar(...)
end