Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

in Lua, how can I use a table as varargs (...)?

strjoin accepts one string and then a variable number of arguments. I'm looking for a way to take a table with a variable number of arguments and use each item in the table as another argument.

local myTable = {
    'a',
    'b',
    'c',
}
-- This is what I want except that I don't want to hard code
-- a specific number of parameters

local myString = strjoin(' ', myTable[1], myTable[2], myTable[3])
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the unpack function:

local myString = strjoin(' ', unpack(myTable))

Newer versions of Lua place the unpack function in the table module:

local myString = strjoin(' ', table.unpack(myTable))

This doesn't answer your question directly, but as lhf pointed out, the following is much more efficient:

local myString = table.concat(myTable, ' ')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...