lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


function compare(a,b)
  a = tostring(tonumber(a) + tonumber(b))
  return a:match"2"
end

As a funny extension of the above, here is a library whose functions
operate on "binary strings" (strings containing only 0's and 1's).
The operands must have lengths between 1 and 16.

-- bit.lua
local MINLEN, MAXLEN = 1, 16

function band(a,b)
  a = tostring(tonumber(a) + tonumber(b))
  return ( a:gsub("[12]", { ["1"]=0, ["2"]=1 }) )
end

function bor(a,b)
  a = tostring(tonumber(a) + tonumber(b))
  return ( a:gsub("2", "1") )
end

function bxor(a,b)
  a = tostring(tonumber(a) + tonumber(b))
  return ( a:gsub("2", "0") )
end

function bnot(a)
  a = a:gsub("[01]", { ["0"]=1, ["1"]=0 })
  return ("1"):rep(MAXLEN - #a) .. a
end

--
Shmuel