Lua replacement for the % operator

风流意气都作罢 提交于 2019-11-30 14:29:38

问题


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

This should work without any problems, but with the Lua in my server the script doesn't run if there is a % in the script... I dont know whats the reason, so is there any "replacement" for that? So I could check the number divsibility?

Thank you.


回答1:


It's not ideal, but according to the Lua 5.2 Reference Manual:

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




回答2:


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




回答3:


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



回答4:


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




回答5:


function mod(a, b)
    return a - (math.floor(a/b)*b)
end



回答6:


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)



来源:https://stackoverflow.com/questions/9695697/lua-replacement-for-the-operator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!