lua-users home
lua-l archive

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


On Mon, Jun 30, 2003 at 06:22:15PM +0900, Dylan Cuthbert wrote:
> What's really nice is the "packing" and "unpacking", ie.
> frog = 10, 20, 30    -- packs frog with 3 numbers
> x, y, z = frog  -- unpacks frog into its 3 separate elements
> 
> Lua would benefit greatly from this kind of feature.

frog={1,3,4}
x, y, z = unpack(frog)

But the elements can be modified. The following wrapper should hie
them:

function pack(...)
    return {unpack=function() return unpack(arg) end}
end

frog=pack(1,2,3)
x, y, z = frog.unpack()

You could also set a metatable with __newindex for the table constructed 
in 'pack' to forbid adding new elements to the table. Or use a userdata?
Or maybe a function?

function pack(...)
    return function(i)
        if not i then 
	    return unpack(arg)
	else
	    return arg[i]
	end
    end
end

frog=pack(1,2,3)
x, y, z=frog()
y=frog(2)

-- 
Tuomo