lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> -----Original Message-----
> From: lua-l-bounces@lists.lua.org [mailto:lua-l-bounces@lists.lua.org]
> On Behalf Of Kevin Martin
> Sent: woensdag 9 mei 2012 14:33
> To: Lua mailing list
> Subject: Construct table from multiple values with named keys
> 
> 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
> 
> The effect I'm looking for is
> 
> > local date = {}
> > date.day, date.month, date.year =
> startdate:match("(%d%d)/(%d%d)/(%d%d%d%d)")
> > print(os.time(date))
> 
> But without declaring the local date.
> 
> Obviously
> 
> > print(os.time({startdate:match("(%d%d)/(%d%d)/(%d%d%d%d)")}))
> 
> doesn't work because the values are assign to indices 1, 2, and 3
> 
> Nor does
> 
> > print(os.time({day, month, year =
> startdate:match("(%d%d)/(%d%d)/(%d%d%d%d)")}))
> 
> 
> because it interprets day and month as values rather than keys.
> 

If you don't want the local, then probably you also don't want an extra
function, if that's no problem then this should work;

local function labelledtable (t1, t2)
    assert(type(t1) == "table" and type(t2) == "table", "expected 2 table
arguments")
    local result = {}
    for i = 1, #t2 do
        result[t1[i] or i] = t2[i]
    end
    return result
end

print(os.time(labelledtable({"day", "month",
"year"},{startdate:match("(%d%d)/(%d%d)/(%d%d%d%d)")})))