How do I create custom Index for my values inside any table?

My idea was to create tables including stats of any player that joins the game.

Plrs.PlayerAdded:Connect(function(Plr)
	PlayerData[Plr.UserId] = {}
	for name, v in PlayerStats do
		table.insert(PlayerData[Plr.UserId], name)
	end
	print(PlayerData)
end)

Both PlayerData and PlayerStats are created manually

I managed to create a table with custom index set as UserID. As I said, those tables will hold information about player stats, however, I did not found any way to table.insert new values into it that ALSO have custom indexes.

Result of my code, first table is what I want to achive, another is added by my script.

image

Any ideas what can I do?

You can add to a table with a custom index by doing someTable["someIndex"] = someValue

Without using table.insert? wouldn’t this just overwrite my values?

Yes, it would overwrite the values. If you wanted to avoid overwriting them, you could try doing something like:

if someTable["someIndex"] then
    someTable["someOtherIndex"] = someValue
else
    someTable["someIndex"] = someValue
end

Does that mean I gotta do IF statement for each “stat” value? What if I have like 10 of those?

And then how am I suppose to reference to table created with

PlayerData[Plr.UserId] = {}

I’m curious as to why you’d want to not overwrite existing indices and instead store the changes in a new index.

?

Plrs.PlayerAdded:Connect(function(Plr)
	PlayerData[Plr.UserId] = {}
	for name, v in PlayerStats do
		PlayerData[Plr.UserId][name] = v
	end
	print(PlayerData)
end)
3 Likes

It works, and its exactly what I needed. Thank you!

Im looping through table I’ve declared. It looks like this:

local PlayerStats = {
	Strength = 0,
	Endurance = 0,
	Agility = 0,
	Intelligence = 0,
}

When Player joins the game, script will get his UserID and make new table named by his ID.
My goal was to insert those values to freshly created user table.

That’s my bad for going off track, it wasn’t clear to me what you wanted, sorry for that

1 Like

No worries about that! Thank you anyway!

1 Like

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