lua - table.concat with string keys

4.9k views Asked by At

I'm having a problem with lua's table.concat, and suspect it is just my ignorance, but cannot find a verbose answer to why I'm getting this behavior.

> t1 = {"foo", "bar", "nod"}
> t2 = {["foo"]="one", ["bar"]="two", ["nod"]="yes"}
> table.concat(t1)
foobarnod
> table.concat(t2)

The table.concat run on t2 provides no results. I suspect this is because the keys are strings instead of integers (index values), but I'm not sure why that matters.

I'm looking for A) why table.concat doesn't accept string keys, and/or B) a workaround that would allow me to concatenate a variable number of table values in a handful of lines, without specifying the key names.

1

There are 1 answers

2
Etan Reisner On BEST ANSWER

Because that's what table.concat is documented as doing.

Given an array where all elements are strings or numbers, returns table[i]..sep..table[i+1] ยทยทยท sep..table[j]. The default value for sep is the empty string, the default for i is 1, and the default for j is the length of the table. If i is greater than j, returns the empty string.

Non-array tables have no defined order so table.concat wouldn't be all that helpful then anyway.

You can write your own, inefficient, table concat function easily enough.

function pconcat(tab)
    local ctab, n = {}, =1
    for _, v in pairs(tab) do
        ctab[n] = v
        n = n + 1
    end
    return table.concat(ctab)
end

You could also use next manually to do the concat, etc. yourself if you wanted to construct the string yourself (though that's probably less efficient then the above version).