Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

how to get the value of an nil index?

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

2 comments

0

Nil indices have no value.

0

can u read my question again

1 answer

✓ Accepted answer

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:

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:

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;
})

2 comments

0

thanks

0

no problem

This discussion is preserved as it was. New answers, comments, and votes are closed.