[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Separator in table concatenation
- From: Luis Carvalho <lexcarvalho@...>
- Date: Sat, 8 Dec 2012 10:54:33 -0500
> It would be nice if table.concat behaved like string.gsub:
> table.concat(tbl,sep)
> would allow `sep` to be not only a string, but also a table or
> function, indexed or called with the current list index.
If `sep` depends on the index then isn't it better to simply "merge" tbl and
a `sep` table and then concat the result?
Alternatively, you might want to have a slightly more general concat function
that pre-formats table entries:
table.gconcat = function (t, sep, format)
local f = format ~= nil and {} or t
if format ~= nil then
assert(type(format) == "function", "function expected")
for i, v in ipairs(t) do f[i] = format(v, i) end
end
return table.concat(f, sep)
end
> E.g.
> tbl = {"A","B","C"}
> enumerate = function(k)
> return ", "..tostring(k+1)..": "
> end
> print("1: "..table.concat(tbl,enumerate))
> 1: A, 2: B, 3: C
format = function (fmt)
return function (v, i) return fmt:format(i, v) end
end
tbl = {"A", "B", "C"}
print(table.gconcat(tbl, ", ", format"%d: %s"))
Cheers,
Luis
--
Computers are useless. They can only give you answers.
-- Pablo Picasso
--
Luis Carvalho (Kozure)
lua -e 'print((("lexcarvalho@NO.gmail.SPAM.com"):gsub("(%u+%.)","")))'