Separating a table in a string with commas [ String Manipulation ]

Hello ! I’m currently learning the bases of string manipulation, pretty interesting though !

However, I have an issue/question.

How can I form a string from a table separated with commas?

Example :

> local table = {"string1","string2"}
> local formattedString = ""
>
> print(formattedString)

(wanted) output:

string1,string2

I hope to have an answer quickly!

If you wanted to convert a table into a string you could do this:

local newstring = ""
for i, v in pairs(table) do
    if i > 1 then
        newstring = newstring .. ", "
    end
    newstring = newstring .. tostring(v)
end
print(newstring)

If you wanted to convert the string back into a table you could do this:

local table = string.split(string, ", ")

When I use the variable “table” or “string” you should convert those into your tables and strings with different names.

You could simplify this by using the table method that pretty much does exactly that:

local tab = {"X", "Y", "Z"}
print(table.concat(tab, ", "))
8 Likes

Sorry for the late response ;

That’s exactly what I was looking for, I think I’ll use table concatenatation method often !

Thanks C#per

1 Like