Log In  


I see % all over and have even copied it but have no idea what it means or does...

For example:

local b=13
local a=flr(b/2)%2

I know this is like beginner stuff. The manual says "Same as (x%1) for positive values of x" under the flr() documentation but the % isn't the same as flr() is it?

And then why is it used?

1


% is the modulo operator, and gives the remainder after dividing two numbers.

For example,

10%8 is 2 (10 divided by 8 is 1 with a remainder of 2)
10%2 is 0 (10 divided by 2 is 5 with a remainder of 0)

not really sure what the documentation is talking about under flr()... x%1 will return the fractional part of the number (stripping off the integer), so:

10.25%1 = 0.25 (10.25 divided by 1 is 10 with a remainder of 0.25).


Additionally, modulo can be used to force numbers to be "cyclical"

If you had something that updated t+=1 every update call, and an array with only 10 elements, it would crash very quickly. However, you can do something like either:

myArray[t%10]
myArray[t%#myArray] --better option since it maps to the array size automatically


There's a gotcha when using a modulo counter to cycle through an array in Lua: arrays start at 1, not 0 like in other languages. t%10 gives you a number from 0-9, not 1-10 like you need: hence you need to add 1 to the modulo result to get the right index.

--Error: tries to access myArray[0] (which will be nil) and skips the last element.
myArray[t % #myArray]

--Correct: accesses the full range of the array.
myArray[(t % #myArray) + 1]


[Please log in to post a comment]