Why does 0 % 5 return 1? when it should return 0

I’m trying to understand this code from @BanTech

--Services
local runService = game:GetService("RunService")

local regionIndex = 0

local SoundRegions = {
	{"City" },
	{ "City" },
	{ "Nature" },
	{ "Nature" },
}

runService.Heartbeat:Connect(function()

	print(0 % 5) -- I get zero here
	regionIndex = regionIndex % #SoundRegions +1
	print(regionIndex) -- but 1 here
end)

RegionIndex is supposed to start at zero and the sum of the table plus one is five.

So when setting regionIndex how does it equal 1?

regionIndex = regionIndex % (#SoundRegions + 1)
This will get you 0. Its gets 1 since the % happens first.

1 Like

It’s because the % does its operation first and then add one, meanign it does 0 % 5 first then adds one to the answer. If you’re trying to add 5 with 1 and then get the modulus for it, do what @TheDCraft mentioned, although taht will still return 0

1 Like

As the other replies mentioned, but perhaps more clearly illustrated here, is that the modulo operator comes first in the order of operations.

regionIndex % #SoundRegions + 1
can be resolved to
0 % 4 + 1
which is equivalent to
( 0 % 4 ) + 1

For the following 5 index possibilities (as you’ve initialised at 0):

0 =>   0 % 4 + 1   =   (0 % 4) + 1   =   0 + 1   = 1
1 =>   1 % 4 + 1   =   (1 % 4) + 1   =   1 + 1   = 2
2 =>   2 % 4 + 1   =   (2 % 4) + 1   =   2 + 1   = 3
3 =>   3 % 4 + 1   =   (3 % 4) + 1   =   3 + 1   = 4
4 =>   4 % 4 + 1   =   (4 % 4) + 1   =   0 + 1   = 1

Therefore you can get indices 1-4 and nothing above or below, so you will always be able to index your SoundRegions table.

2 Likes