How do I get all entries in a table and put them into a string?

Viewed 113

I'm working on a ROBLOX project and I'm trying to make it so that when a player touches a brick (we'll say... a finish line!), it adds them to a table called winners.

How do I get every entry in winners, separate them with a comma (apart from the last one, that would look like: test, test2, test3, which looks weird) and then put them into one whole string to go into a StringValue in ReplicatedStorage.

Here is what I have so far:

...
local winners = {}
...

for _, winner in pairs(winners) do
    winnersVariable.Value = ???
end

Summary: Let's say I had a table (winners) with 3 objects in it (which are strings - {"test1","test2","test3"}). I want to extract all them strings, separate/join them with a comma and then put them into one whole string (for example: test1, test2, test3)

How would I do this?

1 Answers

Either you do it manually using a loop:

local winners = {"Bob", "Jim", "Susanne", "John"}
local winnerList
for _, name in ipairs(winners) do
  winnerList = winnerList and winnerList .. ", " .. name or name
end
print(winnerList)

Or you simply use Lua's table.concat

print(table.concat(winners, ", "))
Related