n_cy
(n_cy)
March 14, 2021, 5:57pm
#1
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?
Heartbeat shouldn’t have as much of an impact. Have you tried performing a different check on each event? For example, if you have 4 regions, you could do one per Heartbeat, therefore doing each region only once per 4 Hearbeats.
If your number of regions is going to be a lot higher, then you might want to do something else, but provided the number is low:
local regionIndex = 0
game:GetService( 'RunService' ).Heartbeat:Connect( function ()
regionIndex = regionIndex % #SoundRegions + 1
…
TheDCraft
(TheDCraft)
March 14, 2021, 5:59pm
#2
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
BanTech
(BanTech)
March 14, 2021, 6:37pm
#4
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