Lua - if语句中的语法错误

时间:2022-06-01 18:16:18

Just tried to execute a small Lua script, but unfortunately I'm doing something wrong. I've no more ideas what the fault might be.

刚尝试执行一个小的Lua脚本,但不幸的是我做错了。我没有更多的想法可能是错误。

function checkPrime( n )
    for i = 2, n-1, 1 do
        if n % i == 0 then
            return false
        end
    end
    return true
end

The interpreter says:

口译员说:

lua: /home/sebastian/luatest/test.lua:3: `then' expected near `%'

I think it's not a big thing and perhaps it's quite clear what is wrong. But somehow I cannot see it at the moment.

我认为这不是一件大事,也许很明显出了什么问题。但不知怎的,我现在看不到它。

2 个解决方案

#1


There is probably some version problem, check your version of lua. The usage of '%' as an infix operator for modulo can only be used in Lua 5.1, in 5.0 it is not supported yet. Try using math.mod instead:

可能有一些版本问题,检查你的版本的lua。使用'%'作为模数的中缀运算符只能在Lua 5.1中使用,在5.0中它尚不支持。尝试使用math.mod代替:

if math.mod(n,i) == 0 then

Edit: Also note that in 5.1, math.mod still exists, but it has been renamed to math.fmod. For now, the old name still works, but support will probably be removed in future versions.

编辑:还要注意,在5.1中,math.mod仍然存在,但它已被重命名为math.fmod。目前,旧名称仍然有效,但在将来的版本中可能会删除支持。

#2


Have you tried wrapping "n% i == 0" in parentheses? Stupid question, but sometimes overlooked!

你试过在括号中包装“n%i == 0”吗?愚蠢的问题,但有时被忽视了!

#1


There is probably some version problem, check your version of lua. The usage of '%' as an infix operator for modulo can only be used in Lua 5.1, in 5.0 it is not supported yet. Try using math.mod instead:

可能有一些版本问题,检查你的版本的lua。使用'%'作为模数的中缀运算符只能在Lua 5.1中使用,在5.0中它尚不支持。尝试使用math.mod代替:

if math.mod(n,i) == 0 then

Edit: Also note that in 5.1, math.mod still exists, but it has been renamed to math.fmod. For now, the old name still works, but support will probably be removed in future versions.

编辑:还要注意,在5.1中,math.mod仍然存在,但它已被重命名为math.fmod。目前,旧名称仍然有效,但在将来的版本中可能会删除支持。

#2


Have you tried wrapping "n% i == 0" in parentheses? Stupid question, but sometimes overlooked!

你试过在括号中包装“n%i == 0”吗?愚蠢的问题,但有时被忽视了!