Need help with basic OOP

I am trying to learn oop and I don’t seem to understand how to insert value in a dictionaty on an oop system.

I want to know how to add stuff inside a dictionary with a function called “Add” and get the values out of it.

But when I try to do it myself like this it shows that the dictionary I am printing is nill!

Module Scipt,

local module = {}
module.__index = module

function module.new(GenWithLocation)
	return setmetatable({
		Assigned = {}
		
	}, module)
end

function module:Add(generatorObj, locationObj)
	table.insert({[generatorObj] = locationObj}, self.Assigned)
end

function module:Print()
	for i, v in pairs (self.Assigned) do
		print(i.Name..' = '..v.Name)
	end
end

return module

Server Script,

wait(8)
print("S")
local mod = require(game.ServerScriptService.Hydroplant)
mod.new()

mod:Add(workspace.Generator1, workspace.Baseplate)
mod:Print()
mod:Add(workspace.Generator1, workspace.Baseplate)
mod:Print()

Both scripts are in ServerScriptService

2 Likes

Error 1 , you need to use object returned by the constructor. Or else you are using the module script as the property table which is not wanted as it’s a function table for the object.

local object1 = mod.new()

object1 :Add(workspace.Generator1, workspace.Baseplate)
object1 :Print()
object1 :Add(workspace.Generator1, workspace.Baseplate)
object1 :Print()

Error 2, table .insert parameters is reversed.

	table.insert({[generatorObj] = locationObj}, self.Assigned)--will insert into dictionary

	table.insert(self.Assigned, {[generatorObj] = locationObj})--inserts into object self
1 Like