This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
cogilv25's profile picture

OOP Inheritance Problem

Started by cogilv25, 01 May 2013 - 11:52 AM
cogilv25 #1
Posted 01 May 2013 - 01:52 PM
I have just started playing around with OOP in lua and don't understand why this doesn't work:


OSObject = {
caption = "Object_Caption",
x=1,
y=1
}

OSLabel = {
__index = OSObject,
New = function(self)
local new = {}
setmetatable(new,{__index = self})
return new
end
}

local lbl = OSLabel:New()
write("lbl.caption = ")
write(lbl.caption)

my understanding would be that OSLabel would inherit caption from OSObject (As it does in c++) and so lbl.caption should equal "Object_Caption" but as far as I can see it equals nil..? so presumably I'm doing something stupid :)/>

Error: bios:156: bad argument: string expected, got nil
Lyqyd #2
Posted 01 May 2013 - 02:14 PM
OSLabel doesn't have a metatable set.
cogilv25 #3
Posted 01 May 2013 - 02:35 PM
OSLabel doesn't have a metatable set.

How Do I give it one..? I don't think I understand metatables properly considering your answer completely threw me off… :/

EDIT: setmetatable(OSLabel, something) somewhere? in OSLabel table?
Sammich Lord #4
Posted 01 May 2013 - 02:38 PM
If I remember how to do metatables correctly you should be able to do:

setmetatable(OSLabel, OSLabel)
cogilv25 #5
Posted 01 May 2013 - 02:40 PM
HAHAHA :D/> fixed it thanks alot Lyqyd I just had to think about what you were saying :)/>

EDIT: thanks for your input Sammich Lord that isn't the way I did it but I will try that :)/> I did:

setmetatable(OSLabel,{__index = OSObject})

under the OSLabel Declaration and I removed __index from OSLabel
cogilv25 #6
Posted 01 May 2013 - 02:46 PM
If I remember how to do metatables correctly you should be able to do:

setmetatable(OSLabel, OSLabel)

Yes you were quite right this also works :)/>