Wrapping index in an array

Normally in a language like Java or C++ this is easy, as Arrays begin with an Index of 0.

In Lua they begin with an Index of 1, meaning that much of the syntax native to Lua for using arrays becomes problematic using a Modulo operation. (% symbol, which gets the remainder of a division.)

--An example of a modulo function in use would be checking for an even number:
function isEven(a)
     return (a % 2 == 0)
end

This can also be used so that you can wrap an index around an array, good for looping systems and making sure you don’t go out of bounds.

--This is how this would look in Lua, but this is where the problems start
local index = i % #array
  1. Because the modulo operator returns a remainder, if you get to the last entry in an array it will return 0 because 10 % 10 = 0
  2. If I just ignore convention and start my array at 0 the syntax for Arrays breaks.
local tab = {}
for i = 0, 10 do
tab[i] = i
end
print(#tab)

--This will print 10 instead of 11, because the # syntax starts at index 1

Any suggestions on how to solve this?

You can achieve zero-based array indexing through the following.

zeroBasedTable = {[0] = val1, [1] = val2, etc.}

Perhaps I need to clarify:

I know I can index on zero, but I’m trying to find a way to handle wrapping around the index (Using Modulo operator) without doing so,

Is this not what you need?
index = (index-1)%length+1

1 Like