How to add a table to a dictionary

Hey you,

So I am currently making a RPG game, and I would like to add players to a table with 2 tools, and then I would like to know how to retreieve that data again.

So my dictionary is:

playerData = {

["Player2"] = {2, 345345};
["Player1"] = {2, 345345}

}

And I know how to retrieve it now (edit):
print(playerData["Player2"][1])

BUT
I do not know how I would add for example a player3, with the same values to the dictionary:
So, I’d like to add this for example:
["Player3"] = {2, 345345}

Somewhere in the dictionary, but how would I do that? Thanks.

I have come this far, but I don’t know how to set the name of the table inside the dictionary:

table.insert(playerData,1,2,545)

Thank you very much for help, and looking forward to your answer :slight_smile:

4 Likes

You can index them by string.
That way you don’t accidentally end up getting the second index when doing Data[2].

Instead, do:

Data["2"]

For arrays, the Lua unpack() function can do most of the work if you want to clone the array.

local original = {1, 3, 5, 7, 9}
local clone = {unpack(original)}
 
for i = 1, #clone do
	print(clone[i])
end

So if I would like to access:

Player2’s second value:

I’d write this: (?)

playerData[1][2]

Nope doesn’t work (edit)

Data[2] would be the second “value”.

Player[1] is the first, if you’re doing [1][2], you’re trying to access the second index if there was one inside the Data[1].

Thanks for your reply, but I am not asking how to clone a dictionary, I am more interested in how to add a table to a dictionary, as I wrote in my post.

If you want to add a value to a dictionary just do:

playerData["Player3"] = {2, 345345}

8 Likes
Table[Player.Name] = {Value1, Value2} -- etc.

This is how you can insert a dictionary.
For arrays, use:

table.insert(Table, <type>)
3 Likes

Thanks for your answer, I get this error though:

Expected identifier when parsing expression, got ‘=’

(It’s something wrong with the “=”)

This works fine on my end:

local playerData = {

["Player2"] = {2, 345345};
["Player1"] = {2, 345345}

}

playerData["Player3"] = {2, 345345}

print(playerData["Player3"][1])

Double check everything is typed correctly.

1 Like

It’s hard to tell what you tried to do as you did not specify any code.
Seems like the one below you figured it out just fine though.

I had a random “-” somewhere in the code lol.