This is just a quick question. I’ve looked around for a while and surprisingly enough I haven’t found how to do this.
How do I instance a value like the following into a table using table.insert:
local tableExample = {
["Name1"] = 42
["Name2"] = 15
}
I understand the basics of table.insert but not sure how to add this type of value.
table.insert(tableExample, 1, ??)
tableExample["Name1"] = Value
?
You can index tables by name, or by their numerical position. It is not recommended to mix the two.
Well, I’m trying to make a global leaderboard table with the key being the player’s id and the subvalue being the total amount donated. Am I going about this the right way?
You don’t need to do use table.insert, simply setting the index of the table to that value would be your solution!
local leaderboards = {}
leaderboards[player.UserId] = 69
print(leaderboards[player.UserId]) —prints 69
1 Like
It seems like a good way to approach it. Though my main concern regarding that would be gaps in the table, as I imagine you wouldn’t have too many userIds in conjunction with each other. I believe using pairs()
to go through the table and using someTable[tostring(userId)]
would be a solution to that.
Reference: Lua Tutorial => Avoiding gaps in tables used as arrays
2 Likes