1

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 Answer 1

4

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, that makes perfect sense, I didn't quite take that it on the first read, thank you!
Just commenting to make you know that there is an unwanted equal sign in the assignment of the "n" variable. Otherwise, thanks for the function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.