lua-users home
lua-l archive

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


On Aug 8, 2010, at 12:29 PM, Jonathan Castello wrote:

> On Sun, Aug 8, 2010 at 12:26 PM, Luiz Henrique de Figueiredo
> <lhf@tecgraf.puc-rio.br> wrote:
>>>>> myModule, myOtherModule = require('moduleM')
>>>> 
>>>> Multiple return values are not supported by require as far as I know.
>>> 
>>> Then perhaps it should? Of course, you can return a table as well.
>> 
>> require can't return multiple values because it caches the value
>> return by the module open function.
>> 
> 
> Could it not put the results in a new table, and unpack() them on
> return? Or is that inefficient?

That's inefficient for the common case though I've been thinking of writing a smart pack/unpack pair that would do something like the following:

local packed = setmetatable( { }, { __mode = 'kv' } )

local none = { n = 0 }

packed[ none ] = none

function smartpack.pack( ... )
	local count = select( '#', ... )
	if count == 0 then
		return none
	elseif count == 1 then
		return ( ... )
	else
		local v = { n = count, ... } -- or table.pack( ... )
		packed[ v ] = v
		return v
	end
end

function smartpack.unpack( v )
	if packed[ v ] then
		return table.unpack( v, 1, v.n )
	else
		return v
	end
end

Basically, the idea is to not bother generating a table for the single value case and to recognize the packed cases by keeping them in a weak set.

For require this is overkill, but it ought to help with other cases where we need to pack up ... into a table but the 0 and 1 value cases are common.

Mark