1

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.

2
  • On an unrelated note, it is perfectly enough to check roots up to math.floor(math.sqrt(n)) instad of n-1, when you want to check if a number is prime or not. Commented Jan 20, 2009 at 21:22
  • That's right, but I use the script only to measure execution times of different scripting languages. Commented Jan 22, 2009 at 14:34

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

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

3 Comments

In parentheses? But then it is a string. As I see it, LUA does not eval it or so...
No, lua does not require parentheses around the expression, since 'if' and 'then' perfectly delimit it.
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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.