Call the master class constructor

You are obviously a lot that enjoyed the easy-go of Lua classes on TI-Nspire, but also noticed that it is too simple to let you work correctly on a specific case. Let’s explain.

This case is the ability to call the master class constructor in the inherited class in order to avoid repetitions. Indeed, if you change one field in the master class, you must change that field in every inherited classes.

Here is an example :

A = class()
function A:init(x)
  self.t = 0
  self.x = x
end
 
B = class(A)
function B:init(x, y)
  self.t = 0
  self.x = x
  self.y = y
end

Here, if we would like to change t = 0 from the master class constructor, we also have to change it in the B class constructor in order to be coherent. Ones could think like that :

A = class()
function A:init(x)
  self.t = 0
  self.x = x
end
 
B = class(A(0, 0)) -- construction of the object before inheriting
function B:init(x, y)
  self.x = x
  self.y = y
end

But here again, the field x is repeated.

One thing we forgot to take care here is that B is an inherited class of A, so, each field of A are obviously in B. But for the constructor, we’re just redefining it. Is there a way to call the previous constructor from A giving B as parameter ?

Actually, yes !

Something important to know in order to understand the solution, is that this :

dummy = class()
function dummy:doSomething()
  self.mark = 0
end
dummy:doSomething()

is exactly the same of that :

dummy = class()
function dummy.doSomething(self)
  self.mark = 0
end
dummy.doSomething(dummy)

or again :

dummy = class()
function dummy:doSomething()
  self.mark = 0
end
dummy.doSomething(dummy)

The colons allow to give as first parameter the object that has this method. So nothing prevents us to not use this tip and then give to the method a manual first parameter as below !

A = class()
function A:init(x)
  self.t = 0
  self.x = x
end
 
B = class(A)
function B:init(x, y)
  A.init(self, x) -- call the A class constructor in order to avoir repetitions
  self.y = y
end

 

Leave a Reply