4

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.

Dillon
  • 151
  • 1
  • 4

1 Answers1

3

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
ratchet freak
  • 47,288
  • 5
  • 68
  • 106