Hi!
It’s great that you’re experimenting with alternative methods! I wish you all the success with further learning.
The function you are using works fine with arrays
, and can handle 'gaps'
or nil
values too. That behaviour could be partially compared with ipairs()
instead of pairs()
, since ipairs()
respects order in arrays, is the fastest of all the functions that can be used for iteration, but stops with it reaches the first ‘gap’.
I think you accidentally left out temp += 1
line inside the repeat loop.
local tab = {"A","B","C","D"}
local i = 1
repeat
local v = tab[i]
print(v)
i += 1
until i > #tab -- #tab == last element, hence > relational operator
i = 0
Although for
-loops and intended functions are the best possible way to interate through a table, it seems worth mentioning some interesting aspects of using repeat loops like this for learning purposes.
- The above code can handle
nil
values (gaps) as well as dictionaries
local mixed_table = {
x = "A",
y = "B",
[1] = "C",
[2] = "D"
}
-->> C D
-
In case a table contains a lot of elements, repeat-loop is going to exhaust
allowed execution time. That could be solved by adding a task.wait()
statement every now and then, for example every time 200 more elements have been iterated. That also depends on how demanding the rest of the logic applied to each element is. pairs()
and other such functions won’t exhaust all allowed time, on the other hand.
-
for
-loops are easier to write and easy to understand.
-
Let’s quickly compare run time:
(Note: this is just a short comparison test and does not represent anything completely definite, as results may vary. However, it can serve us to show that pairs()
is a little bit faster.
Quick test
local REPEATS = 10
local array = table.create(5000,100) -- 5000 elements with the value of 100
local start,finish1,finish2
local sum1,sum2 = 0,0
local average1,average2
local x = 0
local i = 1
for i=1,REPEATS do
start = os.clock() -------------------------------------------------
i = 1
repeat
x += array[i]
i += 1
until i > 5000 -- #tab == last element, hence > relational operator
i = 1
sum1 += os.clock()-start
x = 0
start = os.clock() -------------------------------------------------
for _,v in pairs(array) do
x += v
end
sum2 += os.clock()-start
end
average1 = sum1/REPEATS
average2 = sum2/REPEATS
print((average1>average2 and "pairs()" or "repeat").." was faster:")
print(
math.round(math.max(average1,average2)*100/math.min(average1,average2))/100 ..
" times (approximate average)"
)

The result isn’t a constant number and depends on a variety of minor factors.
Have a nice day!