Thanks very much for the explanation, @ngwese!
I will pick a method, and stick to it
, but great to have some background.
Incidentally, for my current project, I’ve gone for a mixture of Lua modules (where multiple instances with their own properties are not needed) and the above OOP approach where multiple independent entities with identical functionality seems to make more sense.
I’m largely a hobby coder (though I’ve been doing it a long time), so I do tend to get hung up on syntactical and structural concerns (often at the expense of getting the basic functionality to work, sadly, time being limited), so this is all interesting stuff.
Here’s a weird one (or maybe not, and it’s just a symptom of my lack of understanding):
Class = {}
function Class:new(o, val)
o = o or {}
setmetatable(o, self)
self.__index = self
self.reset = false
o.val = val
o.table = {}
return o
end
function Class:changeVal(newval)
self.val = newval
end
function Class:printVal()
print(self.val)
end
function Class:setReset()
self.reset = true
end
print("Create 'Obj1' instance with value of 10")
Obj1 = Class:new(nil, 10)
print("Create 'Obj2' instance with value of 12")
Obj2 = Class:new(nil, 12)
print("Obj1.val = " .. Obj1.val)
print("Obj2.val = " .. Obj2.val)
Obj1:changeVal(400)
Obj1:printVal()
Obj2:printVal()
Obj1:setReset()
print("Obj1 reset value: " .. tostring(Obj1.reset))
print("Obj2 reset value: " .. tostring(Obj2.reset))
produces the following output:
Create 'Obj1' instance with value of 10
Create 'Obj2' instance with value of 12
Obj1.val = 10
Obj2.val = 12
400
12
Obj1 reset value: true
Obj2 reset value: false
I’d have expected both instances to end up with the same values for ‘reset’, in this case, but that doesn’t seem to be the case.