There must be a better way to do this... [Answered]

I just written a function to ‘wrap’ a number which should have a value between -127 and 128… i.e. when the number is 128 and is incremented it should become -127 and when it is -127 and decremented it should become 128.

Flipping back and forth through the lua documentation I’ve come up with something which seems to work but which also seems ugly. Very ugly.

Without further ado:

function wrap(n)
if n>128 then
   n=-128+(n%128)
   return n
elseif n<-127 then
   n=128-(math.abs(n)%128)
   return n
else
   return n
end
end

My question… ladies and gentlemen… is obvious: could you spare a moment to tell me how this should be done?

I’d be much obliged.

you could do something like (n+127+256*10)%256 - 127

actually assuming % in lua works as usual for negative numbers, you can get rid of the 256*10

(n+127)%256 - 127

@ruilov works like a charm and is SO much more elegant. Thank you!

Powerful little thing that modulo operator when used properly. I need to find out more about it.

Is % identical to math.fmod? I have been using the latter, but much prefer the prior.

@jlslate I’m afraid I don’t know. Googling the question it would appear from the LÖVE forum that the % operator is faster than math.fmod but hopefully someone who knows more about this will chime in here.

Quote: “If you can, use % operator instead of math.fmod.” from this thread:
http://love2d.org/forums/viewtopic.php?f=3&t=3500&start=10

Noticeably faster! Thanks!