tags:

views:

718

answers:

2

Hi!

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.

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.

A: 

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

Derek P.
In parentheses? But then it is a string. As I see it, LUA does not eval it or so...
okoman
No, lua does not require parentheses around the expression, since 'if' and 'then' perfectly delimit it.
David Hanak
This is a perfect solution as it causes lua to process the entire expression as a single boolean (and thus avoids the cryptic error message). BTW, it doesn't turn into a string if you do that...
RCIX
+4  A: 

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:

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.

David Hanak
Oh well, I love those enlightening error messages... Thanks!
okoman