How to make a table's identifier a player's UserId?

I am making a saving system and I have a table with other tables in it, holding player data. The main table’s name is “userdata” and the table inside it should be named after the player’s user id.

The problem is it throws an error when I name the table after the player and I don’t know how to fix it.

I have tried setting the name to a default name and then changing it after, but then it deletes all the data the table is containing.

This is kind of hard to explain, but here is what I want:

-- What the main table should look like--
local userdata = {
 ["ExampleUserID-data"] = {--User data--},
}

-- How I am tryng to set up the table --
function PlayerAdded(Player)
   local Player.UserId .. "-data" = {
     -- Default user data --
   }
   table.insert(userdata, Player.UserId .. "-data")
end 

It is the local Player.UserId that is throwing the error, if anyone can help it would be appreciated.

-Thanks

1 Like

Do you mean like this?

local userdata = {
	["ExampleUserID-data"] = {--User data--},

	},
}

-- How I am tryng to set up the table --
local function PlayerAdded(Player)
	local ID = Player.UserId

	userdata[ID .. "-data"] = {"PUT STUFF HERE"
		-- Default user data --
	}
	--table.insert(userdata, Player.UserId .. "-data")
end 

game.Players.PlayerAdded:Connect(function(Plr)
	PlayerAdded(Plr)
end)

print(userdata)
2 Likes

Yes, thank you, it worked! I just don’t understand how userdata[ID .. "-data"] works because wouldn’t that just search for the value in the table, not add it?

The difference between writing to the key and reading from key is simple:

local tab = {}

tab.New = "newdata" -- adding new data to key

if tab.New == "newdata" then -- reading from the key
     print(tab,tab.New)
end
local UserData = {}
game.Players.PlayerAdded:Connect(function(Player)
	UserData[Player.UserID.."-data"] = {}
end)

As small as I could get it.

It would under normal circumstances but because the field indexing is directly followed by an assignment operator (=), Lua is essentially instructed that some value is going to be assigned as the value associated with the indexed field of the referenced table.