Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

?how would I change a tables Index Name

so the problem i encountered was that

function module.ReturnStats(Player)
	local DataStoreTable = {
		UserId = Player.UserId, 
		Stats = {},
		EverythingOwned = {}
		}
	
end

So To Index this table I'd have to do DataStoreTable and call on it

Is there a way for me to change the name DataStoreTable to Players UserId So i can access it easier

1 answer

I'm not sure exactly what you mean, but with metatables, you can extend your module and simply reference the data using self.

Script

local PlayerClass = require ( script:WaitForChild('ModuleScript') )

local function PlayerJoined(Player) 
	local PlayerData = PlayerClass.new(Player)
	print ( PlayerData:ReturnStats() )
end

game.Players.PlayerAdded:Connect(function(Player)
	PlayerJoined( Player )
end)

game.Players.PlayerRemoving:Connect(function(Player)
	local LocatePlayer = PlayerClass.locateplayer(Player)
	if LocatePlayer then 
		LocatePlayer:testprint()
	end
end)

for _, Player in pairs(game.Players:GetPlayers()) do 
	PlayerJoined(Player)
end

ModuleScript

local module = {}
module.PlayersData = {}
module.__index = module

function module:ReturnStats(Player) 
	-- self is the DataStoreTable
	return self.Stats
end
function module.new(Player)
	-- Set sub fallbacktable to module for the methods
	local DataStoreTable = setmetatable({
    Player = Player;
	PlayerName = Player.Name;
	UserId = Player.UserId, 
    Stats = {},
	EverythingOwned = {}}, module)
	-- Index DataStoreTable for lookups
	module.PlayersData[Player.Name] = DataStoreTable
	return DataStoreTable
end

function module:testprint() 
	print ( self.PlayerName, 'left' ) 
end

-- could be subbed out for a meta method
function module.locateplayer(Player)
	module.PlayersData[Player.Name]
end

return module

This discussion is preserved as it was. New answers, comments, and votes are closed.