Metatables not working

Basically, i call a function named playerJoined which returns data from my module, but data:test() isn’t working despite it being defined (i might be understanding this wrong)

heres the module:

local Data = {};
Data.__index = Data;

Data.Profiles = {};

local Modules = script.Parent;

local ProfileService = require(Modules.ProfileService);

local DataStore = ProfileService.GetProfileStore({
	Name = script:GetAttribute("DataStoreName"),
	Scope = script:GetAttribute("Scope");
}, {
	Bux = 30000,
	Items = {},
	Gems = 0,
	Tix = 0,
	Cases = 1,
})

function Data.PlayerJoined(player)
	warn("LOADING")
	local profile = DataStore:LoadProfileAsync(tostring(player.UserId), false, "ForceLoad");
	local self = {};
	
	if profile and player then
		warn("Loading 1/4")
		if player.Parent then
			warn("Loading 2/4")
			profile:AddUserId(player.UserId);
			profile:Reconcile();
			
			profile:ListenToRelease(function()
				player:Kick("Your data is released.");
				Data.Profiles[player.UserId] = nil;
			end)
			
			if Data.Profiles[player.UserId] then
				Data.Profiles[player.UserId]:Release();
				player:Kick("Your data was already loaded in this session. Please rejoin.");
			else
				warn("Loading 3/4")
				self.__index = self;
				self = profile;
				self = setmetatable(self, {});
				Data.Profiles[player.UserId] = self;
				warn("Loaded 4/4");
				return self;
			end
		end
	end
	return self;
end

function Data:test()
	print(self);
end

return Data;

Script:

local Modules = script.Parent.Parent.Modules;

local rakeData = require(Modules.RakeData);


function playerAdded(player)
	local data = rakeData.PlayerJoined(player);
	warn(data)
	data:test();
end

for i, v in pairs(game.Players:GetPlayers()) do
	playerAdded(v);
end
game.Players.PlayerAdded:Connect(playerAdded)

Error: ServerScriptService.Scripts.Module Execution:9: attempt to call missing method 'test' of table

1 Like

That is because you’re not setting the metatable of the new object you’re making to Data. You should define self as setmetatable(self, Data). Then do everything as normal.

2 Likes

Oh I knew it would be something small haha. Thanks man!

2 Likes

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