OOP Additional Support

Hello.

I am working on a side project for fun and I wanted to try and use OOP while scripting it and I was just wondering if someone can see what I’m doing wrong so far and maybe show me the correct way to do it?

I am getting this in the output.

Handler (CLIENT - LOCAL SCRIPT)

--// Services
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService('ReplicatedStorage')
local RunService = game:GetService('RunService')

--// Items
--# Player
local Player = Players.LocalPlayer
local Mouse = Player:GetMouse()

--# Phone UI
local Container = script.Parent.Parent.Container

--# Storage
local Storage = ReplicatedStorage:FindFirstChild('Storage')

local Events = Storage:FindFirstChild('Events')
local Modules = Storage:FindFirstChild('Modules')

--# Variables
local Phone = require(script.Parent)

--// Scripts
--# Build Start
local function init()
	Phone.new(Container)
	
	Phone:log()
end

init()

Client (CLIENT - MODULE)

local Phone = {}
Phone.__index = Phone

--// Scripts
function Phone.new(passedContainer)

	--# Items
	local self = {}

	--# Set
	setmetatable(self, Phone)

	--# Properties
	self.Container = passedContainer
	
	self.phoneOwner = 'PHONEOWNER'
	
	--# Initialize
	print("Initialized phone metatable!")
	
	print(self)

	return self
end

--# Set Open
function Phone:log()
	print(self)
	print(self.phoneOwner..' is logged.')
end

return Phone

image

I have looked up tutorial on OOP on the devforum but I was just looking for some more explanation.

I’m not sure why as I do not have much experience myself, but my guess is the problem is on this line.

print(self.phoneOwner..' is logged.')

The error comes from the script trying to concatenate a nil value with a string. In this case the nil value is self.phoneOwner, although I’m not quite sure why it is nil, as it seems to be defined properly.

You’re returning a new object, so you should set that as a variable:

local function init()
	local phone = Phone.new(Container)
	
	phone:log()
end
1 Like

How would I go about accessing phone if I needed to use a separate script ?

You would either have to add it to a separate ModuleScript after you create it or add it to the global _G table