Search code examples
luaconcatenationlua-table

Lua table.concat


Is there a way to use the arg 2 value of table.concat to represent the current table index?

eg:

 t = {}
 t[1] = "a"
 t[2] = "b"
 t[3] = "c"

 X = table.concat(t,"\n")

desired output of table concat (X):

 "1 a\n2 b\n3 c\n"

Solution

  • Simple answer : no.

    table.concat is something really basic, and really fast.

    So you should do it in a loop anyhow.

    If you want to avoid excessive string concatenation you can do:

    function concatIndexed(tab,template)
        template = template or '%d %s\n'
        local tt = {}
        for k,v in ipairs(tab) do
            tt[#tt+1]=template:format(k,v)
        end
        return table.concat(tt)
    end
    X = concatIndexed(t) -- and optionally specify a certain per item format
    Y = concatIndexed(t,'custom format %3d %s\n')