Object-oriented problem

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
gotokiichi
Prole
Posts: 6
Joined: Wed Jan 29, 2020 7:41 pm

Object-oriented problem

Post by gotokiichi »

I got rxi's simple OOP library classic.lua from adnzzzzZ's BYTEPATH tutorial, and I tested it with some simple inheritances:

Code: Select all

Object = require 'classic'

ClassA = Object:extend()
function ClassA:new(x)
	self.x = x
	print(self.x)
end

ClassB = ClassA:extend()
function ClassB:new(x)
	ClassB.super:new(x)
end

ClassC = ClassA:extend()
function ClassC:new(x)
	ClassC.super:new(x)
end

local a = ClassA('a')
local b = ClassB('b')
local c = ClassC('c')

print(b.x)
I thought result should be as:
a
b
c
b

but I got:
a
b
c
c

Did I make something wrong or the library has some flaw to fix?
Attachments
test.lua
(367 Bytes) Downloaded 164 times
classic.lua
(1009 Bytes) Downloaded 157 times
Nelvin
Party member
Posts: 124
Joined: Mon Sep 12, 2016 7:52 am
Location: Germany

Re: Object-oriented problem

Post by Nelvin »

The devil is in the detail.

To call into constructors of parent classes you need to call them like so

Code: Select all

    ClassB.super.new( self, x )
This is, because ClassB etc. are class instances and when you use super:new and not use the explicit self of the current scope, you call those upper constructors with the actual class instance rather than your object instance.
gotokiichi
Prole
Posts: 6
Joined: Wed Jan 29, 2020 7:41 pm

Re: Object-oriented problem

Post by gotokiichi »

Nelvin wrote: Sun Feb 16, 2020 7:11 am The devil is in the detail.

To call into constructors of parent classes you need to call them like so

Code: Select all

    ClassB.super.new( self, x )
This is, because ClassB etc. are class instances and when you use super:new and not use the explicit self of the current scope, you call those upper constructors with the actual class instance rather than your object instance.
Thank you Nelvin, I got it, seems I shall care more about ':' in lua:D
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Google [Bot] and 102 guests