[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Multiple returns & list constructors
- From: Rici Lake <lua@...>
- Date: Wed, 18 Aug 2004 10:07:37 -0500
On 18-Aug-04, at 7:01 AM, David Given wrote:
Unfortunately, multiple returns from a function are only concatenated 
to the
list if the function is the *last* thing on the list. If it's 
somewhere in
the middle of the list, only the first item is added.
...
Are there any workarounds I can use to fix this? I can have fn() 
return a
table, in which case the table gets added to the list, but it's still 
added
as a single item where I actually want the contents of the item 
instead...
Perhaps you should flatten the table afterwards, if the objects are not 
themselves tables.
Otherwise, you could use a metamethod:
do
  local meta = {}
  function meta:__add(more)
    for i = 1, table.getn(more) do table.insert(self, more[i]) end
    return self
  end
  function list(t)
    return setmetatable(t or {}, meta)
  end
end
-- example
function several(str, count)
  local rv = {}
  for i = 1, count do table.insert(rv, string.format("%s%i", str, i)) 
end
  return unpack(rv)
end
> return unpack(list{1, 2, 3}+{several("foo", 7)}+{4, 5, 6})
1       2       3       foo1    foo2    foo3    foo4    foo5    foo6    
foo7    4       5       6