I’m getting my head around using classes/objects using the inbuilt approach offered by LuaBind. However because Lua is so flexible with how you do things and doesn’t restrict you, I’m not sure I’m taking the right approach.
Consider the following code:
class 'Farm' function Farm:__init() self.num_chickens = 0 end function Farm:Add_Chicken() self.num_chickens = self.num_chickens + 1 return Chicken(self) end class 'Chicken' function Chicken:__init(Farm) self.host_farm = Farm self.mother = false end function Chicken:Lay_Egg() return Egg(self) end class 'Egg' function Egg:__init(Chicken) self.parent = Chicken end function Egg:Hatch() self.parent.mother = true return self.parent.host_farm:Add_Chicken() end -- Testing old_mcdonald = Farm() chicken = old_mcdonald:Add_Chicken() egg = chicken:Lay_Egg() new_chicken = egg:Hatch() print(old_mcdonald.num_chickens) -- Should be 2 print(chicken.mother) -- Should be true print(new_chicken.mother) -- Should be false
While this works, is this the right way of doing things?
It doesn’t seem right to me that that the ‘egg’ object should change the states of ‘chicken’ and ‘farm’ objects, but I can’t think of a better way to achieve the same outcome.
Just interested for my own understanding and wonder if any seasoned programmers could offer a view?