I would like to find a away to directly start to read my loops from a different index.
For exemple :
local t = {'red', 'yellow', 'green', 'purple'}
for i,v in pairs(t) do
print(i,v)
end
I would like for exemple to directly start from the third index so it prints only ‘3 green’, ‘4 purple’.
I need this because i use very long tables and skipping a lot of indexes will improve performance a lot since i have to read tables every frames for a replay system.
pairs() returns a function with the following contract: passing a table and index returns the next index and value. This is the same function as next()
local i = 3
repeat
i, v = next(t, i)
--Do loop actions
until i == nil
In your case, the indexes are numbers so you could just start a numeric for loop at an index other than 1. But the above method also works for other key types:
local t = {['red'] = 10, ['yellow'] = 35, ['green'] = 2, ['purple'] = 100}
local i = 'yellow'
repeat
i, v = next(t, i)
--Do loop actions
until i == nil
However, this is not super useful as the order of non-number keys is not really knowable (it might be predictable in the case of strings), since it is a hash table. Order is just not something it gives you.