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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With