Learning OOP (Attempted nil)

You can write your topic however you want, but you need to answer these questions:

  1. Learn OOP By changing a simple brick color by inserting variables for later another function fire it

  2. ServerScriptService.Script:6: attempt to call a nil value (Script)

(Module)

local Tyger = {}
Tyger.__Index = Tyger




function Tyger:Fire(Tygers) 
	Tygers._Part.BrickColor = BrickColor.new("Really red")

	print(Tyger,"Tyger")
end
	
function Tyger.New(Part)
	
	local self = setmetatable({},Tyger)

	self._color = BrickColor.new("Really red")
	self._Part = Part
	
	print(self)
	Tyger:Fire(self)
	return self
end

return Tyger

(SCRIPT)

local Module = require(game:GetService("ReplicatedStorage").ModuleScript)
local Brick = workspace.Part

local Tygerz = Module.New(Brick)

Tygerz:Fire()
2 Likes

I believe .new is a constructor so you probably don’t need Tyget:Fire(self) in there. Also I think this would work:

local Tyger = {}
Tyger.__Index = Tyger

function Tyger:Fire() 
	self._Part.BrickColor = self._color
	print(Tyger,"Tyger")
end
	
function Tyger.New(Part)
	local self = setmetatable({},Tyger)

	self._color = BrickColor.new("Really red")
	self._Part = Part
	
	return self
end

return Tyger

Script:

local Module = require(game:GetService("ReplicatedStorage").ModuleScript)
local Brick = workspace.Part

local Tyger = Module.new(Brick)
Tyger:Fire()

However I’m relatively new to OOP as well, so don’t take my word for anything.

2 Likes

That’s because you’re using __Index, not __index which is the correct metamethod; note the lowercase i.

local meta = {} 
meta.__index = meta 
meta.test = true 
local mt = setmetatable({}, meta) 
print(mt.test) --> true
local meta = {} 
meta.__Index = meta 
meta.test = true 
local mt = setmetatable({}, meta) 
print(mt.test) --> nil

Also, you don’t have to manually pass the object to itself when you’re declaring functions like that since self is automatically defined:

function Tyger:Fire() 
	self._Part.BrickColor = BrickColor.new("Really red")
	print(self,"Tyger")
end
4 Likes

change this to:

Tyger.__index = Tyger

.__index shouldn’t be capitalised.

3 Likes

Solve:

ModuleScript

local Tyger = {}
Tyger.__index = Tyger

function Tyger:Fire(Tygers) 
	Tygers._Part.BrickColor = BrickColor.new("Really red")

	print(Tyger,"Tyger")
end

function Tyger.New(Part)

	local self = setmetatable({},Tyger)

	self._color = BrickColor.new("Really red")
	self._Part = Part

	print(self)
	Tyger:Fire(self)
	return self
end

return Tyger

Server Script Or LocalScript

local Module = require(script.ModuleScript)
local Brick = workspace.Part

local Tygerz = Module.New(Brick)
Tygerz:Fire()

Even to know more about OOP you can check this article by me to understand some stuff:

2 Likes