lua-users home
lua-l archive

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


Although it's a dirty hack, these routines would give somewhat of an equivalence to bitwise operators. I can understand why they were included explicitly in Lua, what with Lua_number being a float. For something that you'd set here and there, but not for something that'd be hit a few million times a second.

-- bit_set
-- Returns the flag power of 2 bitwise ior'ed into set
function bit_set( set, flag )
  flag = math.pow(2, flag)
  if math.mod((set/flag), 2)==0 then
    set = set + flag;
  end
  return set;
end

-- bit_set
-- Returns the flag power of 2 bitwise and'ed from set
function bit_clear( set, flag )
  flag = math.pow(2, flag)
  if math.mod((set/flag), 2)==1 then
    set = set - flag;
  end
  return set;
end

-- bit_toggle
-- Returns the flag power of 2 bitwise toggled in set
function bit_clear( set, flag )
  flag = math.pow(2, flag)
  if math.mod((set/flag), 2)==0 then
    set = set + flag;
  else
    set = set - flag;
  end
  return set;
end

-- bit_test
-- Returns true or false, if the flag power of 2 is in set.
function bit_test( set, flag )
  flag = math.pow(2, flag)
  if math.mod((set/flag), 2)==1 then
    return true
  else
    return false;
  end
end

William C. Bubel