lua-users home
lua-l archive

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


On Tue, Mar 19, 2013 at 2:56 PM, phil anc <philanc@gmail.com> wrote:
> I am not interested in full-fledged OO (no information hiding, no
> polymorphism, ...), I only want a memory-efficient and simple way of
> associating methods to objects.
>
> ...And I don't want to wrap my head every time around metatables and __index
> :-)   so I came up with the following 'class' definition:
>

Metatables aren't terribly difficult, really. Here's how I usually
define objects:

local myObject, myObjectMethod = {}, {}

function myObject.new(t)
    local self = {x=t.x, y=t.y, z=t.z, w=t.w or 1, h=t.h or 1}
    return setmetatable(self, {__index=myObjectMethod})
end

function myObjectMethod:print_xyz()
    print("x=", self.x)
    print("y=", self.y)
    print("z=", self.z)
end

return myObject

This method does "hide" the methods table, but you can easily return
it or add a reference in myObject if you want. (Or someone can
getmetatable(myObject.new()) if they really want it)

You might also do:

local function myObject_new(_, t)
    local self = {x=t.x, y=t.y, z=t.z, w=t.w or 1, h=t.h or 1}
    return setmetatable(self, {__index=myObjectMethod})
end

setmetatable(myObject, {__call=myObject_new})

That will let you write: foo = myObject {x=1, y=2, z=3}
instead of: foo = myObject.new {x=1, y=2, z=3}


-- 
Sent from my Game Boy.