Hello!
I’m making a cart ride game for fun, But this is my first time trying to use MetaTables for something.
I think i’ve done everything Correctly, but when i call print in the :Init() function, it prints the value.
But if i return that same value in a function, or just plain try to print it in a different function in the metatable it returns the Memory Adress and Not the value.
I’m completely lost since to me metatables are still really confusing.
Here’s the ModuleScript:
local cartFolder = workspace.Map.Carts
local CollectionService = game:GetService("CollectionService")
-- || Module
local cartManager = {
Tag = "Cart"
}
function cartManager:Init()
local self = setmetatable({
Tag = cartManager.Tag,
List = CollectionService:GetTagged(self.Tag),
Amount = #CollectionService:GetTagged(self.Tag),
}, cartManager)
print(self.List) -- Prints Amount
print(self.Amount) -- Prints Amount
-- || Setup Watch Connections for Cart Creation
CollectionService:GetInstanceAddedSignal(self.Tag):Connect(function(newInstance :Instance)
self.List[newInstance.Name] = {
Owner = nil,
Model = newInstance,
}
end)
CollectionService:GetInstanceRemovedSignal(self.Tag):Connect(function(oldInstance :Instance)
self.List[oldInstance.Name] = nil
end)
-- || End of Watch Connections
return self
end
function cartManager:testPrint()
return self.List
end
function cartManager:IsPlayerInCart(player :Player?)
return self.List[self.Tag.. player.Name] or false
end
function cartManager:DestroyAll()
for _, Cart :Model in pairs(cartFolder:GetChildren()) do
Cart:Destroy()
end
self.List = {}
end
function cartManager:MakeCart(TargetLocation :CFrame, TypeOfCart :string)
local newCart :Model = script[TypeOfCart]:Clone()
if newCart then
newCart:PivotTo(TargetLocation)
-- || Do This Last to Ensure Script Completion
newCart:AddTag(self.Tag)
end
return newCart
end
-- || Cosmetic Functions
function cartManager:Amount()
print(self.Amount) -- Prints Memory Adress
return self.Amount
end
function cartManager:List()
print(self.List) -- Prints Memory Adress
return self.List
end
return cartManager
And Here’s the server script that calls the module, [this was just testing]:
local CollectionService = game:GetService("CollectionService")
local cartFolder = workspace.Map.Carts
local cart = require(script.Carts)
cart:Init()
cart:MakeCart(CFrame.new(-23.9415703, 2.32410991, 39.5611038, 1, 0, 0, 0, 0, -1, 0, 1, 0), "DefaultCart")
while task.wait(5) do
print(cart:List()) -- Prints Memory Adress
print(cart:Amount()) -- Prints Memory Adress
end
And Here’s the output:
Any help is greatly appreciated!
If you need any more information, let me know.
i’ll be happy to provide!