lua-users home
lua-l archive

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


I have a newbie's question. I apologise if this is a FAQ, but here 
goes. This email is quite long but not that complex. 

I have code like this:

***class.lua
local function new(self)
        local obj = {}
        setmetatable(obj,{__index=self})
        return obj
end

local function repr(self,msg)
        print(msg,self)
        print(self.fruit.sort,self.fruit.type,self.fruit.taste)
        print(self.ashes)
        print("---")
end

local fruit = {
        sort = "mango",
        type = "ripe",
        taste = "smooth"
}

local ashes = "oz"

class = {
        new   = new,
        repr  = repr,
        fruit = fruit,
        ashes = ashes
}

return class
***

based very loosely on stuff I learned in chapters 15 and 16 of 
Programming in Lua. (I haven't bought it yet, but only because my 
local bookstore doesn't have it. I hope to order through them, in 
case they get a couple and put the spare ones on the shelf :-)

Then I wrote this:

***tester.lua
require "class"

o1 = class:new()
o2 = class:new()

o1:repr("o1 before")
o2:repr("o2 before")

o1.ashes = "england"
o1.fruit.sort = "banana"

o1:repr("o1 after")
o2:repr("o2 after")
***

and, perhaps unsurprisingly but probably disappointingly, got this:

o1 before       table: 0x8077070
table: 0x8077350
mango   ripe    smooth
oz
---
o2 before       table: 0x8077528
table: 0x8077350
mango   ripe    smooth
oz
---
o1 after        table: 0x8077070
table: 0x8077350
banana  ripe    smooth
england
---
o2 after        table: 0x8077528
table: 0x8077350
banana  ripe    smooth
oz
---

Does this mean that the object doesn't inherit tables from the parent 
class, or does it mean that it inherits a "shallow copy" of the table 
from the parent? Or what? The objects seems to have their own "ashes"
but not their own "fruit"...

5~