How to convert a table of listed items into a string?

I have a table like so

{
    Player1, Player2, Player3
}

And I wanna return it to a string, like

Label.Text = TableContents

and the string would be written like

Player1, Player2, Player3

Couldn’t you just concat the table?

local ConcattedTable = table.concat(PlayerTable, " ")
Label.Text = ConcattedTable
local Table = {"String", "String", "String"}

Table = table.concat(Table, ", ")

EDIT: Sorry, concat already returns a string

1 Like

If the table elements are instances you can’t concatenate them like strings. Your only option is to iterate through it yourself.

function customConcat(list, sep)
	if (#list == 0) then
		return ""
	end
	local buildStr = ""
	for _, element in ipairs(list) do
		buildStr = buildStr..sep..tostring(element)
	end
	return string.sub(buildStr, #sep + 1) -- cut off the extra comma
end

We can create a new table which consists into the previous tables variable names.

local TableThing =  {Player1, Player2, Player3}

local TableThingStringTable = {
P1 = tostring(TableThing.Player1),
P2 = tostring(TableThing.Player2),
P3 = tostring(TableThing.Player3)
}

local ValuesStringLine = TableThingStringTable[1]..TableThingStringTable[2]..TableThingStringTable[3]

print(ValuesStringLine)

in case you want to get actual player names(Instead of just variable names), you can just use their name like this :

local TableThing =  {Player1, Player2, Player3}

local TableThingStringTable = {
P1 = Player1.Name,
P2 = Player2.Name,
P3 = Player3.Name
}

local ValuesStringLine = TableThingStringTable[1]..TableThingStringTable[2]..TableThingStringTable[3]

print(ValuesStringLine)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.