lua-users home
lua-l archive

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


Hello,

This topic is certainly not Lua-specific, but may be more relevant here because we can freely define inheritance schemes. The most common one is certainly indirect inheritance, where attributes not found on an object are looked up through indirection to the object's "type" -- using __index=Type.

This works fine as long as attributes are simple, not composite ones (in Lua, not tables). Setting an attribute value will actually end up creating it on the object itself, which breaks indirection. But what if the attribute is a kind of record? When setting an entry of the record, not the record itself, no record is created on the object, so that the change happens on the type's attribute and finally applies to all objects sharing it. (See sample code.)

I have no idea how to simply deal with this. And even less how to design a general solution for an all-purpose OO framework. Maybe non-function attrs should be copied at creation time? Or only tables? But then, how to have really common attrs on the type? Require them to be set them on a special __common sub-table (to which the type's __index would point)?

---------------------------------------------------------------------
Point = {u=0, pos={x=0,y=0}, col={H=0,S=0,L=0}}
Point.__call = function(Point, p)
    p = p or {}
    return setmetatable(p, Point)
end
Point.__tostring = function(p)
    local x,y = p.pos.x,p.pos.y
    local H,S,L = p.col.H,p.col.S,p.col.L
    local u = p.u
    return string.format (
           "Point{u=%s, pos={x=%s,y=%s}, col={H=%s,S=%s,L=%s}}",
           u, x,y, H,S,L )
end
Point.__index=Point
setmetatable(Point, Point)

p1,p2 = Point(),Point()
p1.u = 3
p1.pos = {x=1,y=2}
p1.col.H = 180
print (p1) ; print(p2)
--> Point{u=3, pos={x=1,y=2}, col={H=180,S=0,L=0}}
--> Point{u=0, pos={x=0,y=0}, col={H=180,S=0,L=0}}

Denis
-- 
________________________________

la vita e estrany

spir.wikidot.com