11

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])
Asa Ayers
  • 4,854
  • 6
  • 40
  • 57

2 Answers2

24

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, ' ')
Judge Maygarden
  • 26,961
  • 9
  • 82
  • 99
  • 1
    I had to use `table.unpack` instead of just `unpack`. Might be a version difference. – Stefan Monov Mar 08 '18 at 11:02
  • I too had to use `table.unpack`. This may be do to the ["new module system" introduced in Lua 5.1](https://www.lua.org/versions.html). – Sled May 22 '18 at 20:02
  • Yes, the unpack function was moved to the table module in Lua 5.2. This answer is 8 years old. So, I couldn't predict the future. ;) I've updated the answer. – Judge Maygarden Jun 08 '18 at 22:26
6

Use table.concat instead of strjoin.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • While technically you are correct, your answer was not chosen because I am looking for a solution I can also apply to some other similar functions. – Asa Ayers Aug 13 '10 at 14:21
  • 1
    @AsaAyers, then you'd better find/request from devs functions that would work with tables because your program will fails once you try this with table of 200+ values, as it will overflow Lua local function stack. – Oleg V. Volkov Oct 04 '13 at 15:50