Formatting a list?

:wave:

I was wondering if it was possible to format a list/array?

Let’s say I have this:

local names = {
    'bob';
    'joe';
    'susan';
    'heather';
}

Is there a way to properly create a list with those names? Currently, I have this:

local str = ''
for i,v in ipairs(names) do
    local add
    if i == 1 then
        add = ''
    else
        add = ', '
    end
    if i == #names then
        add ..= 'and '
    end
    add ..= v
    str ..= add
end
print(str) --> bob, joe, susan, and heather

Is there a way to do this easier than what I have?

you can use table.concat(table,",")

Yes, using the concat function.

table.concat(names, ",") --> will concatenate items in table names separated by comas.

Here’s the full syntax:

@Nube762, @Dehydrocapsaicin,

Is there a way to add the “and” when the last item is reached? I assume I’d have to specify the i, j arguments but I was wondering if there was any built-in method to do this or if I would have to do that manually.

Maybe try:

local names = {
    'bob';
    'joe';
    'susan';
    'heather';
}
lastItem = names[#names]
print(string.gsub(table.concat(names, ", "), lastItem, "and " .. lastItem))
1 Like