I'm stuck on a problem to do with OOP and metatables. The code examples below are bare bones sort of things.
I've got a base class:
BaseObject = {
tag = "",
new = function(self)
local new = {}
setmetatable(new, {__index = self})
return new
end,
_draw = function(self) end,
_event = function(self, event, a, b, c) end,
}
And 2 classes that inherit from it:
Label = {
__index = BaseObject,
--!! important bit:
textColor = colors.white,
backgroundColor = colors.black,
--!!
new = function(self)
local new = {}
setmetatable(new, {__index = self})
return new
end,
_draw = function(self)
--...
end,
}
Box = {
__index = BaseObject,
--!! important bit:
textColor = colors.white,
backgroundColor = colors.black,
--!!
new = function(self)
local new = {}
setmetatable(new, {__index = self})
return new
end,
_draw = function(self)
--...
end,
}
Then I have a third class (also inheriting from the base class) that contains an instance of the previous two classes:
TextField = {
__index = BaseObject,
box = nil,
label = nil,
textColor = colors.red,
backgroundColor = colors.white,
new = function(self, textc, backc)
local new = {}
setmetatable(new, {__index = self})
new.box = Box:new(...)
new.label = Label:new(...)
-- Notice this bit
new.textColor = textc
new.backgroundColor = backc
new.box.textColor = new.textColor
new.box.backgroundColor = new.backgroundColor
new.label.textColor = new.textColor
new.label.backgroundColor = new.backgroundColor
end,
_draw = function(self)
--...
end
textfield = TextField:new(colors.brown, colors.green)
-- blah stuffs stuffs
-- Notice this bit again
textfield.textColor = colors.orange
textfield.backgroundColor = colors.purple
textfield.box.textColor = ...
...
......
}
With the 2 "notice this bit"s in the last code example, how can I avoid having to set the box's and label's text and background colors every time I change the text field's text and background colors? How can I avoid having to do this once I create an instance of the TextField? Basically, how can I update the box's and the label's background and text colors as the textfield's one changes? I'd like to keep them all in sync, without having to do it manually with 6 lines of code each time. I would like for each of the classes to have their own text and background colors, as they can all be used independently.
Thanks for any help :)/>