Lua - if语句中的语法错误

刚刚尝试执行一个小 Lua 脚本,但是不幸地出了一些问题。我已经没有什么更好的想法了,不知道故障可能在哪里。

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

解释器提示错误:

lua: / home / sebastian / luatest / test.lua: 3:“预计 `then' 附近的%” 

我认为这不是什么大问题,也许很明显是什么错了。但是某种原因,我现在无法看到它。

原文链接 https://stackoverflow.com/questions/462976

点赞
stackoverflow用户45615
stackoverflow用户45615

将下面翻译成中文并且保留原本的 markdown 格式

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

你有试过在 "n% i == 0" 周围加括号吗?这是一个愚蠢的问题,但有时会被忽视!

2009-01-20 20:36:42
stackoverflow用户42136
stackoverflow用户42136

可能存在版本问题,请检查你的lua版本。在Lua 5.1中,以'%'为中缀运算符表示取模运算可以正常使用,但在5.0中尚未支持。请尝试使用 math.mod 代替:

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

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

2009-01-20 20:48:13