How to make the concat of list of boolean?

Viewed 76

How I can to concat the boolean values?

I've tried this but get the error that the boolean values are not good for table.concat

local tabl = {true, false, true, false, "question", 42}
print (table.concat (tabl, ', '))
2 Answers

Lua's type coercion works between numbers and strings. That doesn't include bool values.

There's at least 2 ways to resolve this:

  1. Manually create the output
  2. Re-map the table and use table.concat again

I'm going to explain the first option here as it won't increase the amount of times you need to loop over the table.

local tabl = {true, false, true, false, "question", 42}
local output = ""
for i,value in pairs(tabl) do
    output = output .. tostring(value)
    if i ~= #tabl then
        output = output .. ", "
    end
end

print(output) -- true, false, true, false, question, 42

If this is something you use often, you could turn it into a function

function table_safe_concat(tabl, sep)
    local output = ""
    for i,value in pairs(tabl) do
        output = output .. tostring(value)
        if i ~= #tabl then
            output = output .. sep
        end
    end

    return output
end

local tabl = {true, false, true, false, "question", 42}
print(table_safe_concat(tabl, ", "))

For Performance Sake

I've added this example using a temporary table in the case that string concatenations will cause performance issue.

function table_safe_concat(tabl, sep)
    local tmp_table = {}
    for i,value in pairs(tabl) do
        table.insert(tmp_table, tostring(value))
    end

    return table.concat(tmp_table, sep)
end

local tabl = {true, false, true, false, "question", 42}
print(table_safe_concat(tabl, ", "))

The proper way to go here is to map the table to a table of strings and then call table.concat; manually using concatenation results in quadratic performance due to Lua always having to copy the entire immutable string when appending.

I'd first write a map function (that doesn't modify the original table):

local function map(tbl, func)
    local mapped = {}
    for k, v in pairs(tbl) do mapped[k] = func(v) end
    return mapped
end

then simply call table.concat(map(tabl, tostring), ', ').

Bonus: If you're using any Lua standard library extensions (f.E. Penlight, Lume etc.), chances are map is already implemented.

Related