My Lua-Function to do the nthPrime exercise runs perfectly on my compiler. But when i try to get it verified in the exercism editor, I get this error message:
./nth-prime_spec.lua:11: attempt to call a boolean value (upvalue 'nth')
What is wrong?
This is my function:
local function nthPrime(n)
if n < 1 or n%1 ~= 0 then
return "error"
end
local testPrime = 1
local currentNumber = 0
local currentPrime = 0
while true do
testPrime = testPrime + 1
for i=2, testPrime, 1 do
if i == testPrime then
currentNumber = currentNumber + 1
currentPrime = testPrime
break
elseif testPrime%i == 0 then
break
end
end
if n == currentNumber then
return currentPrime
end
end
end
May you please explain a bit more? My function takes in a value ‘n’ and gives the nth-prime of it out. I don’t understand what the error message means. Where is it calling a boolean value? What exactly do I need to change to get the output accepted?
The test file expects your module to return a value. That value is a function (that the test file names nth). What do you need to do in nth-prime.lua to return a function?
Look carefully at the error message
./nth-prime_spec.lua:11: attempt to call a boolean value ...
The error is coming from line 11 of the test suite. That will answer “Where is it calling a boolean value?”
If your module does not return a value, then local nth = require('nth-prime') assigns true to nth.
There’s another optimization to be made: the loop for i=2, math.sqrt(n), 1 has twice as many iterations as necessary. You don’t need to test i = 4, 6, 8, … because even numbers (except 2) cannot be prime.
if n%2 == 0 then return false end
for i=3, math.sqrt(n), 2 do
if n%i == 0 then
return false
end
end