Lua replacement for the % operator

前端 未结 6 1663
臣服心动
臣服心动 2020-12-30 19:39

I want to check, if a number is divisible by another number:

for i = 1, 100 do
    if i % 2 == 0 then
        print( i .. \" is divisible.\")
    end
end


        
相关标签:
6条回答
  • It's not ideal, but according to the Lua 5.2 Reference Manual:

    a % b == a - math.floor(a/b)*b

    0 讨论(0)
  • 2020-12-30 20:10

    Use math.fmod(x,y) which does what you want:

    Returns the remainder of the division of x by y that rounds the quotient towards zero.

    http://www.lua.org/manual/5.2/manual.html#pdf-math.fmod

    0 讨论(0)
  • 2020-12-30 20:11

    Use math.fmod, accroding lua manual math.mod was renamed to math.fmod in lua 5.1.

    0 讨论(0)
  • 2020-12-30 20:14

    Lua 5.0 did not support the % operator.

    Lua supports the usual arithmetic operators: the binary + (addition), - (subtraction), * (multiplication), / (division), and ^ (exponentiation); and unary - (negation).

    https://www.lua.org/manual/5.0/manual.html

    Lua 5.1 however, does support the % operator.

    Lua supports the usual arithmetic operators: the binary + (addition), - (subtraction), * (multiplication), / (division), % (modulo), and ^ (exponentiation); and unary - (negation).

    https://www.lua.org/manual/5.1/manual.html

    If possible, I would recommend that you upgrade. If that is not possible, use math.mod which is listed as one of the Mathematical Functions in 5.0 (It was renamed to math.fmod in Lua 5.1)

    0 讨论(0)
  • 2020-12-30 20:24
    function mod(a, b)
        return a - (math.floor(a/b)*b)
    end
    
    0 讨论(0)
  • 2020-12-30 20:29
    for i = 1, 100 do
        if (math.mod(i,2) == 0) then
            print( i .. " is divisible.")
        end
    end
    
    0 讨论(0)
提交回复
热议问题