what im trying to do is getting the value of an nil index, like if there was only 3 values in the table and i tried to index a 4th index in the table. it would return the 1st value; index a 5th index = 2nd value. i know i can just subtract the index by the length of the table, but that wont work for most indexes.
local array = {10,30,40,50,60} print(array[6]) -- i want it to print the first index which is 10 print(array[7]) -- 30 print(array[8]) -- 40 -- i can only index with a nil index up to a 10th index until it returns nil using index - #array print(array[11-#array]) -- nil print(array[10-#array]) -- 60
Whenever you need a value that wraps around like you just mentioned, the first thing that should come to mind is the modulo operator %
also called the remainder operator. The modulo operator receives two operands and returns the remainder when the first is divided by the second. For example, 17 % 5 = 2
and 5.6 % 1 = 0.6
. This logic leads to the following solution:
```lua local array = {10 , 30 , 40 , 50 , 60}
function wrap(n , x) return (n - 1) % x + 1 --% has higher precedence then + end print(array[wrap(5 , #array)]) --60 print(array[wrap(234 , #array)]) --50 print(array[wrap(-2 , #array)]) --40 ``` If we want, we can also use metatables to further abstract this logic away:
lua
local array = setmetatable({10 , 30 , 40 , 50 , 60} , {
__index = function(array , i)
return array[wrap(i , #array)]
end;
__newindex = function(array , i , v)
array[wrap(i , #array)] = v
end;
})