This is because in your example, they are not using a table, but rather a dictionary. The different is that arrays’ indexes/keys are just the simple 1, 2, 3 that are set automatically when a table is created with predefined entries or when something has been added to it, these indexes refer to the value in that position.
But dictionaries can use any type of key, even strings.
Example:
local fruits = {"Apple", "Banana", "Pear"}
for i,v in pairs(fruits) do
print(i,v)
end
--Expected output
1 Apple
2 Banana
3 Pear
Whereas a dictionary:
local diction = {
["Name"] = "Steve",
["Food"] = "Apple"
}
for key,value in pairs(diciton) do
print(key,value)
end
--Expected output
Name Steve
Food Apple
What’s basically happening is when the module is required, it creates an empty sessionData table, and when setupPlayerData
is called, it adds a new dictionary entry in the dictionary that contains the player’s userId as the key and a table of what data to store as the value in that dictionary.
Say you have an empty table and setupPlayerData
is called on you, and you have 10 money and your userid is 1625. After that call, if you print sessionData, it would give
{
[1625] = {Money = 10}
}
Assuming that Money
in that example is going to be a dictionary key.
And then in ChangeValue
, it checks if there’s a valid entry that contains the userid of the player, and if there is, get the dictionary key using the specified name
and set its value to whatever is given.
Say you call it using the same player, giving Money
as the name
and 100
as the value
, the line in the if statement woudl look like this
sessionData[1625]["Money"] = 100
Which would do expected, get the key in sessionData using the player’s id, then from that result, get the Money key, and then set its value. The only problem is that there’s no check as of now in that example that check if a valid name was given
The principle works the same if you were to use a table instead of a dictionary, but instead you’d just use table.insert
and reference an index, but in this case we need a non incremental index, so a dictionary is needed