for loop with sorted dictionary keys

Discussion and feedback on Construct 2

Post » Wed Dec 10, 2014 3:52 pm

Hi,

It would be great if it were possible to have the keys in a dictionary sorted during a loop execution. While dictionaries per definition do not define a sort order for keys -- dictionaries are merely associative storage, it would nevertheless be useful to be able to travers all keys in a sorted manner.

Right now, I load the dictionary keys into an array, sort the array, and then loop through the array and access the dictionary via the the keys sorted in the array -- it works well, but is rather memory intensive and cumbersome.

thanks,

Dan
B
8
S
4
G
1
Posts: 205
Reputation: 1,354

Post » Wed Dec 10, 2014 4:26 pm

They don't need to be sorted because they're named unlike arrays which require an order/position. If you want to sort them you could add a number to their name and use a normal for each loop and get them like that, otherwise why not use an array to begin with?

(not actual code)

add key "item0" set value whatever.
add key "item1" set value whatever….

for "sort" from 0 to key count

Dictionary.Get("item"&loopindex("sort")) and do whatever.
Last edited by Ethan on Wed Dec 10, 2014 4:32 pm, edited 1 time in total.
B
43
S
22
G
20
Posts: 735
Reputation: 11,977

Post » Wed Dec 10, 2014 4:32 pm

Thanks @Ethan,

I do use the keys of a Dictionary, for example, to store player names, and dictionary values, to store some values associated with each player, say, number of time the player played a game.

When outputting this information, its useful to have the players sorted -- despite being internally stored in a dictionary.

Dan
B
8
S
4
G
1
Posts: 205
Reputation: 1,354

Post » Wed Dec 10, 2014 4:44 pm

So your wanting to sort them based on the stored value. I see your point now.
B
43
S
22
G
20
Posts: 735
Reputation: 11,977

Post » Wed Dec 10, 2014 4:45 pm

Not exactly, sort them by player name -- I guess you meant that ...
B
8
S
4
G
1
Posts: 205
Reputation: 1,354

Post » Wed Dec 10, 2014 8:56 pm

Maybe create multiple 'Player' dictionaries at runtime, one per player? You can then pick them by giving the dict an instance var and storing the player name/id in there.
Don't lose your work. Backup your game with Dropbox.
B
44
S
10
G
10
Posts: 1,106
Reputation: 9,187

Post » Mon May 25, 2015 4:37 pm

I want to make a top 10 highscore screen, and I currently use a dictionary to save scores ("name of player",score). All I want is to show a screen with the top 10 sorted by the score and showing the name associated to it. I simply don't know how to do it in construct...
B
4
Posts: 4
Reputation: 214


Return to Construct 2 General

Who is online

Users browsing this forum: rovacado, tarek2 and 1 guest