Even/Odd comparison

Posted by tobiassjosten on Mon 30 May 2005 10:38 AM — 5 posts, 34,315 views.

Sweden #0
I can't seem to find a way to check wether a number is odd or even. I've tried with type() (which just gives 'number') and string.find(tostring(number), "."). String.find didn't prove very helpful, despite being my best bet. :/ I tried escaping the dot (is it in regexp format?) but it didn't work either. Anyone got any suggestions as to how I could do this?

The purpose is to get this function to output a centered text:
function visLine(msg, color)
    lnum, rnum = (74 - string.len(msg)) / 2, (74 - string.len(msg)) / 2
    if not string.find(tostring(lnum), "\.") == false then rnum = lnum + 2 end
    ColourTell("lightgrey", "", string.rep("-",lnum) .. " [ ")
    ColourTell(color, "", msg)
    ColourNote("lightgrey", "", " ] " .. string.rep("-",rnum))
end
#1
Use the math.mod function to find the remainder of your number from dividing by 2. If the result is 0, it's even. Otherwise, it's odd.

if math.mod(num, 2) == 0 then
  print("even")
else
  print("odd")
end
Sweden #2
Kind of makes sense to use the math-functions for integers. :P
Thanks alot!
Australia Forum Administrator #3
Another approach which doesn't use division is to use the "bit" extension in the MUSHclient Lua implementation.

eg.


isodd = bit.band (x, 1)


Strangely I couldn't find these functions documented anywhere on this site. If someone can find the URL please let me know.

In summary, MUSHclient has a "bit" table which implements bitwise operations, for use in cases like this.


bit.shr

Shift right - shift arg1 right by arg2 bits

eg.


print (bit.shr (64, 2))  --> 16



bit.shl

Shift left - shift arg1 left by arg2 bits

eg.


print (bit.shl (64, 2))  --> 256




bit.band

Bitwise and ("and" is a keyword) - takes multiple arguments

eg.


print (bit.band (15, 7, 3))  --> 3



bit.bor

Bitwise or ("or" is keyword) - takes multiple arguments

eg.


print (bit.bor (1, 4, 8))  --> 13



bit.xor

Exclusive or - takes multiple arguments

eg.


print (bit.xor (15, 1))  --> 14



bit.neg

Bitwise negate (ones complement as a 32-bit unsigned number)

eg.


print (bit.neg (15))  --> 4294967280

Russia #4
The post with the introduction of Lua bit functions is at:

http://www.gammon.com.au/forum/bbshowpost.php?bbsubject_id=4907