[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Construct table from multiple values with named keys
- From: Tom N Harris <telliamed@...>
- Date: Wed, 09 May 2012 19:00:04 -0400
On 05/09/2012 08:52 AM, Luiz Henrique de Figueiredo wrote:
Given a function that returns multiple values, is there a way to construct a table, but where each value is assigned a name rather than an index
You'll need a helper function:
function namedtable(name,...)
...
local t=namedtable({"day", "month", "year"},f())
for k,v in pairs(t) do print(k,v) end
Since you'd probably repeat that with the same names, returning a
function would work well. This function preserves the numeric keys, like
many database libraries do.
function columns(...)
local name = table.pack(...)
return function(...)
local t = table.pack(...)
if t.n == 0 then return nil end
local n = math.min(name.n, t.n)
t.n = nil
for i = 1,n do
t[name[i] or 0] = t[i]
end
return t
end
end
function parsedates(str)
local date = columns("day", "month", "year")
local match = string.gmatch(str, "(%d%d)/(%d%d)/(%d%d%d%d)")
return function()
return date(match())
end
end
for date in parsedates("28/07/1993 16/12/2011") do
print(os.date("%a %b %e, %Y",os.time(date)))
end
--
- tom
telliamed@whoopdedo.org