String return to nil? OOP Module script

(Sorry for bad grammar)

Hello, I have studied OOP myself like Inheritance and Composition, etc. And deep inheritance chain so I can understand why it can be messy.

Problem:
I notice when I try to add string to my code it return nil except it work for number. Any idea to fix this problem (that I already guess that’s common problem). You don’t need to answer entire script. :wink:

Here’s my (awful) module script.

local Entity = {}
Entity.__index = Entity

function Entity.new(name)
	local self = setmetatable({
		Name = name
	}, Entity)
	
	return self
end

function Entity:PrintInfo()
	print("Name: " .. self.Name)
end

local Character = {}
Character.__index = Character
setmetatable(Character, { __index = Entity })

function Character.new(name, hp, level)
	local self = Entity.new(name)
	setmetatable(self, Character)
	
	self.HP = hp
	self.Level = level
	
	return self
end

function Character:PrintInfo()
	Entity:PrintInfo(self)
	print("HP: " .. self.HP)
	print("Level: " .. self.Level)
end

local PlayerCharacter = {}
PlayerCharacter.__index = PlayerCharacter
setmetatable(PlayerCharacter, { __index = Character })

function PlayerCharacter.new(name, hp, level, xp)
	local self = Character.new(name, hp, level)
	setmetatable(self, PlayerCharacter)
	
	self.XP = xp
	
	return self
end

function PlayerCharacter:PrintInfo()
	Character:PrintInfo(self)
	print("XP: " .. self.XP)
end

return {
	Entity = Entity,
	Character = Character,
	PlayerCharacter = PlayerCharacter
}

Here’s how I call it in script

local chain = require(ReplicatedStorage.Folder.Entity)
local pc= chain.PlayerCharacter.new("Alex", 100, 80, 1000)

Why do you need metatable OOP?
Indexing singular method with such inheretance is like doing 1 index but at price of 3 perfomance wise.
Consider switching to ECS or different OOP technique Strictly typed <<Object Oriented Programming>> (Better than metatable OOP)

Anyway you better to return class constructors right awey without doing module.new stuff.

Game development is firstly about perfomance so you must reject most of high level language habbits.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.