Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Can't set table to 1st element out of a dictionary help?

I have the dictionary:

Ranks = {
		first = { Salary = 200},
		second = {Salary = 275},
		third = {Salary = 350},
		fourth = {Salary = 500},
		fifth = {Salary = 1000},
},

And I want to set a table in the datastore as that table but it won't show up in the datastore plugin for my data:

	PlayerSesStats[player.UserId].JobStats.Rank = job.Ranks[1]

Also when I do print(~~~location of the dictionary~~~.Ranks[1]) it outputs nil. Help?

2 comments

0

1 ~= "first"

0

then how would i get the 1st table out of the dictionary?

2 answers

✓ Accepted answer

To index a dictionary with a string key, put the key in square brackets after the dictionary (this works woth any key):

print(Ranks["first"])

Also FYI, you can iterate through a dictionary, and the index becomes the key and the value is the table:

for Index,Value in pairs(Ranks) do
	print(Index,Value)
end

Each iteration, Index will be the keys (the words first, second, third, etc.) and the tables associated with them.

If you want to index it by a number, you should make it an array (integer keys) rather than a dictionary. This cn be achieved by simply removing the keys:

Ranks = {
        { Salary = 200},
        {Salary = 275},
        {Salary = 350},
        {Salary = 500},
        {Salary = 1000}
}

Then, you can simply go:

print(Ranks[2].Salary)

which would print 275.

3 comments

0

yes but when the player reaches a certain level i want their rank to upgrade and i was thinking i could do Ranks[x+1], x being their previous rank. i could just simply do Ranks["first"] but i need the value by their position in the table not by the key.

0

Edited

0

i figured it out myself but thank you!

you are using string keys, and 1 is not equal to "first", it would makes thing (especially future casees) WAY less complicated, also number keys dont need to be made clear, as long as they are defined in propper order

Ranks = {
	{Salary = 200},
	{Salary = 275},
	{Salary = 350},
	{Salary = 500},
	{Salary = 1000},
},

2 comments

0

i know 1 isnt equal to first but i thought [1] would mean the 1st element even if the keys name was something else other than first

0

whenever you target an element in a table via square brackets it find an element OF THE NAME specified in the [], so [1] finds "1" (or just 1) and ["first"] finds an item by the name of "first", with string keys, no value is first, neither is any value last

This discussion is preserved as it was. New answers, comments, and votes are closed.