lua-users home
lua-l archive

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


Hi Dylan,

> Lua would benefit greatly from this kind of feature.

Well, I think that Tuomo pointed out that you can realise this by
introducing your own userdata without the __newindex metamethod.  You could
give it an unpack method such that

    x, y, z = my_3d_vector:unpack()

does what it suggests.  I think that this would be particularly suited for
your vector type.

On the other hand, I think that Python tuples can be emulated by Lua tables
(arrays) if you use a proxy.  Simple approach:

do
local meta = {
    __index = function(self, index)
            return self.as_table[index]
        end,
    __newindex = function()
            error "tuples are immutable!"
        end,
}

function tuple(...)
    local t = {as_table = arg}
    setmetatable(t, meta)
    return t
end
end

local tup = tuple(10, 20, 30)

print(tup[2])
local x, y, z = unpack(tup.as_table)
tup[2] = 25  -- error!


Note that in this simple approach you can still screw up beacuse the
as_table member is freely available.  A more involved approach would be to
hide the original table completely, leaving the proxy table empty.  Then the
__index metamethod gets just a little more complicated, because it should
also take care of an unpack method etc.

--
Wim