Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to Modulus in Lua

Tags:

lua

modulus

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 image 437
Dillon Avatar asked Oct 29 '25 17:10

Dillon


1 Answers

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
like image 74
ratchet freak Avatar answered Oct 31 '25 11:10

ratchet freak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!