lua-users home
lua-l archive

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


On Thu, Jul 17, 2008 at 5:06 PM, Michael Gerbracht <smartmails@arcor.de> wrote:
> Sorry for this really simple question but at the moment I can not find the
> answer by myself although I think it's really simple. If I have a function
> that returns more than one value - how do I get them into a table? I need
> something like this:
>
> function test()
>  result = some table of results
>  return unpack(result)
> end
>
> local t = {}
> t = pack(test())
> print(t[2])
>
> Unfortunately there is no pack command, but I am sure it can be done
> somehow. Please assume that I can't change the function itself, otherwise
> the best solution would be to change the function to "return result" of
> course ;-)

This may be overkill, but I use the following solution:

-- Utility functions that let us capture and release output
local hijacknil = setmetatable({}, {__tostring=function() return "nil" end})
local function capture(...)
	local tbl = {}
	for i=1,select("#", ...) do
		local item = select(i, ...)
		if type(item) == nil then
			tbl[i] = hijacknil
		else
			tbl[i] = item
		end
	end
	
	return tbl
end

local function release(tbl, s)
	s = s or 1

	if s > #tbl then
		return
	end

	local item = tbl[s]
	if item == hijacknil then
		return nil, release(tbl, s + 1)
	else
		return item, release(tbl, s + 1)
	end
end

This allows me to handle embedded nils.  Usage:

local results = capture(test())
print(results[2])

If you then need to unpack this, you could use unpack.. but I use
release() instead.  It allows me to handle the embedded nils without
having to know anything about them. It works quite well for where I
need it :P

- Jim