Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Sorting a table of functions by index, but how?

Asked by 3 years ago

I would like to make a table of functions. Functions have their indexes represented as a level id (e.g. 100, 101, 200, 201, 202...) to change some level properties (lighting, gravity ect) So here is an example:

01local functionsTable = {}
02 
03functionsTable[100] = function()
04    print("This is a function number 100")
05end
06 
07functionsTable[101] = function()
08    print("This is a function number 101")
09end
10 
11functionsTable[201] = function()
12    print("This is a function number 201")
13end

You might ask, what's the problem? And a problem comes whenever a player connects to a server, and to apply all property changes in the past, my client script loops trough all of the functions in a table until it reaches current player's level. For example:

01local functionsTable = {}
02local plrLevelId = 200
03 
04functionsTable[100] = function()
05    print("This is a function number 100")
06end
07 
08functionsTable[101] = function()
09    print("This is a function number 101")
10end
11 
12functionsTable[201] = function()
13    print("This is a function number 201")
14end
15 
View all 40 lines...

Not only it skips a function that supposed to called in the order, but it called a function number 101, while function number 100 should be called first. What magic is this? How to go through all functions in a correct order that I assigned by index? Thank you in advance

1 answer

Log in to vote
1
Answered by
imKirda 4491 Moderation Voter Community Moderator
3 years ago
Edited 3 years ago

pairs loops in randomized order, thus it can sometime loop through 201 first but sometime through 101 first. Your solution is ipairs which goes strictly by order, what you do is get all the indices, sort them and loop through them. Since ipairs loops by incrementing the index by one, it can't loop 101 -> 200, it will break instantly, it is expected to loop like 1 -> 2 -> 3 -> 4 ..., that's the reason you create list of indices.

01local functionsTable = {}
02local plrLevelId = 200
03 
04functionsTable[100] = function()
05  print("This is a function number 100")
06end
07 
08functionsTable[101] = function()
09  print("This is a function number 101")
10end
11 
12functionsTable[201] = function()
13  print("This is a function number 201")
14end
15 
View all 37 lines...

about ipairs

about table.sort

ipairs vs pairs

0
Very interesting solution, thank you MrSuperKrut 167 — 3y
Ad

Answer this question