[SOLVED] OOP issue with using metatables and classes

I’m making a simple ordering system that uses an “Order” class module and it has functions like :AddItem() and :RemoveItem(). I believe my code should work as intended, but it keeps throwing an error. Here is the code for both the Order Module and LocalScript:

Module:

local Order = {}
Order.__index = Order

function Order.new()
	local self = setmetatable({}, Order)
	self.Items = {}
	return self
end

function Order:AddItem(item)
	table.insert(self.Items, item)
end

function Order:RemoveItem(item)
	table.remove(self.Items, table.find(self.Items, item))
end


return Order

LocalScript:

local Order = require(game:GetService("ReplicatedStorage").Order)
local currentOrder = nil

currentOrder = Order.new()
currentOrder:AddItem("Burger")
print(currentOrder.Items)

Error:

I’ve read over other posts for the same error but the solutions don’t fix my code. Would greatly appreciate any help, thanks.

2 Likes

I believe you have an issue with how you are setting up the metatable, maybe try this instead:

function Order.new()
	local newOrder = {}
	setmetatable(newOrder, Order)
	newOrder.Items = {}
	return newOrder
end
3 Likes

The error still happens unfortunately.

I just tested your code in a test place and it worked fine. Just from a read through, it looks like it should work anyway.

It might be to do with initialising currentOrder as nil, that’s the only thing I can think of. Are you using this object anywhere else in the script?


setmetatable will return the first parameter passed to it after the metatable has been set, your code and the code the OP used produce the exact same effect.

The code is fine. The only thing I can think of is that you’re referencing the wrong module in the first line of the local script.

Yeah, I need to be able to access the order everywhere in the script hence why it’s defined at the start and then updated throughout. Still really don’t know why it’s working for everyone else but myself.

have you tried just testing in an isolated script? with no other functionality.

The only logical problem I can think of is you’re incorrectly managing your currentOrder variable and somewhere in your script it gets set to nil.

Managed to fix the issue by myself in the end, it was about the way it’s set to nil, appreciate everyone’s contributions!

2 Likes

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