simplification
Download
27 lines 1.3 KiBMoonScriptModified 2026-11-07 raw
123456789101112131415161718192021222324252627
-- This file defines functions for the bitwise operators, which code compiled from Nomsu
-- uses on every Lua version, so the compiled code doesn't depend on the Lua version.
-- On LuaJIT and Lua 5.2, they wrap the bit/bit32 libraries, and check for metatable
-- functions like "__bxor" for bit.bxor(), the way Lua 5.3's built-in operators do.
if jit or _VERSION == "Lua 5.2"
    bitlib = if jit then require('bit') else bit32
    ret = {k,v for k,v in pairs(bitlib)}
    for {name, metamethod} in *{{"bnot", "__bnot"}, {"band", "__band"}, {"bor", "__bor"},
        {"bxor", "__bxor"}, {"lshift", "__shl"}, {"rshift", "__shr"}}
        fn = bitlib[name]
        ret[name] = (x, y)->
            for operand in *{x, y}
                mt = getmetatable(operand)
                if mt and mt[metamethod] then return mt[metamethod](x, y)
            return fn(x, y)
    return ret

-- Lua 5.3+ has built-in bitwise operators. This is loaded from text, since older
-- versions of Lua can't parse them.
return load([[return {
    bnot = function(x) return ~x end,
    band = function(x, y) return x & y end,
    bor = function(x, y) return x | y end,
    bxor = function(x, y) return x ~ y end,
    lshift = function(x, y) return x << y end,
    rshift = function(x, y) return x >> y end,
}]])!