Reputation: 151
In Lua, as you may know, arrays start with index 1.
In other languages I will often use modulus to make a value oscillate through the members of an array, for example:
i = (i + 1) % array.length
return array[1]
How can I do this in Lua, where array[0]
is nil by default.
Upvotes: 4
Views: 1184
Reputation: 48216
Like Egor said in the comments,
First do the modulo and then increment the value.
If i
is equal to the length it will end up 0. Incrementing that will result in 1
. Every other value just gets incremented.
This only works when incrementing by 1 though. For bigger steps you can do
i = (i+n-1)% #array + 1
Upvotes: 3