Re: Construct table from multiple values with named keys
[
Date Prev][
Date Next][
Thread Prev][
Thread Next]
[
Date Index]
[
Thread Index]
- Subject: Re: Construct table from multiple values with named keys
 
- From: Luiz Henrique de Figueiredo <lhf@...>
 
- Date: Wed, 9 May 2012 09:52:43 -0300
 
> 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=table.pack(...)
		local n=t.n
		t.n=nil
		for i=1,n do
			local v=t[i]
			t[i]=nil
			t[name[i] or 0]=v
		end
		return t
	end
	
	function f()
		return 100,200,400
	end
	
	local t=namedtable({"day", "month", "year"},f())
	for k,v in pairs(t) do print(k,v) end