Inheritance help

Here’s an example “a” class.

local a = {};

a.new = function(b)
	local s = {};
	s.b = b;
	return setmetatable(s, {__index = a})
end

function a:c()
	print(self.b)
end

return a;

“a” inherits “d”.

local d = {};
local a = require(script.Parent.a)
setmetatable(d, {__index = a})

d.new = function(b)
	local s = a.new(b);
	s.e = b;
	return setmetatable(s, {__index = d})
end

function a:f()
	print(self.b, self.e)
end

return a;

Now when I do this,

require(workspace.d).new(3):f() -- 3, nil

So self.e is nil. Why is that? It should be 3, 3.

First off, you should set __index directly after you define the class, so local a = {} becomes two lines:

local a = {}
a.__index = a

Then, in the constructor, you set the metatable of the returned table to the class itself, so in the a class, line 4 becomes two lines:

local s = {}
setmetatable(s, a)
...
return s

Follow the same principles in your d class.
I suspect that making these changes should fix the issue.
Here’s a very great tutorial on object orientation.

Following these principles, the a class would become:

local a = {};

a.new = function(b)
	local s = {};
	setmetatable(s, a)
	s.b = b;
	return s
end

function a:c()
	print(self.b)
end

return a;

and the d class would become:

local a = require(script.Parent.a)


local d = {};
d.__index = d

d.new = function(b)
	local s = a.new(b);
	setmetatable(s, d)
	s.e = b;
	return s
end

function d:f()
	print(self.b, self.e)
end

return d;

(I also completely forgot to mention that your d class actually returns a, and also sets the f method of a, instead of d.)

2 Likes

Yeah. Whoops, it worked once I changed the “a” references to “d”.

Yeah I caught that when I was reorganizing the classes. Do you understand how you should be handling classes now, though?

1 Like