Lua 如何实现无符号整数的%运算符?

Lua 如何实现无符号整数的%运算符?,lua,modulo,Lua,Modulo,如何为lua的无符号整数实现%运算符或函数? 我曾想过使用类型转换来浮动,但精度是个问题 function ModU(a, b) if b == 0 then return a end if a == 0 then return 0 end if b < 0 then if a < 0 then if a < b then return b-a else return a

如何为lua的无符号整数实现%运算符或函数? 我曾想过使用类型转换来浮动,但精度是个问题

function ModU(a, b)
    if b == 0 then return a end
    if a == 0 then return 0 end

    if b < 0 then
        if a < 0 then
          if a < b then return b-a 
          else return a 
          end
       else 
          return a
       end
    else
        if a > 0 then return math.tointeger(a % b) 
        else 
            i = ModU(x & 0x7fffffff + 1, b)
            j = ModU(2^31 - 1, b)
            return ModU(i + j, b)
        end
    end
end
功能模块(a、b)
如果b==0,则返回结束
如果a==0,则返回0结束
如果b<0,则
如果a<0,则
如果a0,则返回math.tointeger(a%b)
其他的
i=ModU(x&0x7fffff+1,b)
j=ModU(2^31-1,b)
返回模块(i+j,b)
结束
结束
结束
函数无符号_mod(x,y)

返回yyou应将a表示为常量0+常量1*b+常量2*b^2+…+常数n*b^n,完成后,结果显然是常数0。所以你找到n,这样b^(n-1)b@bogl我认为答案应该比我的评论更正式/完整;我也不确定这就是OP所期待的for@AndrewKashpur我懂了。这只是一个想法。祝您有个美好的一天!此函数在lua<5.3语法中无效,因此您需要将其置于条件
load
中,以便与旧lua兼容。@val-当然,此函数仅适用于lua 5.3+。OP的问题是关于Lua中的整数,5.3之前的Lua没有整数。
function unsigned_mod(x, y)
   return y<=x and x<0 and x-y or y<0 and x or ((x>>1)%y*2+(x&1)-y)%y
end