Dillon
Dillon

Reputation: 151

Alternative to Modulus in Lua

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

Answers (1)

ratchet freak
ratchet freak

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

Related Questions