Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua - "attempt to compare number with nil" error

a={51,31,4,22,23,45,23,43,54,22,11,34}
colors={"white","white","white","white","white","white","white","white","white","white","white","white","white","white","white","white","white"}
function try(f, catch_f)
    local status, exception = pcall(f)
    if not status then
        catch_f(exception)
    end
end
function refreshColors(yellowEndIndex,redIndex,blueIndex)
        for ccnt=1,table.getn(a),1 do
                if ccnt < yellowEndIndex then
                    colors[ccnt] = "yellow"
                elseif ccnt == redIndex then
                    colors[ccnt] = "red"
                elseif ccnt == blueIndex then
                    colors[ccnt] = "blue"
                else
                    colors[ccnt] = "white"
                end
        end
end
try(refreshColors, function(e)
    print("Error Occured - "..e)
end)
refreshColors(1,1,1)
print(colors[1])

When the refreshColors() function is called, it throws an exception and the error message is "Error Occured - trial.lua:11: attempt to compare number with nil". Why the exception occurs although there is no such comparisons in the refreshColors() function?

like image 830
manthosh Avatar asked Feb 11 '13 21:02

manthosh


2 Answers

The error is on line 11, which means:

if ccnt < yellowEndIndex then

There's your comparison with a number. We know ccnt is a number (it's initialised at the start of the loop), so yellowEndIndex must be nil. 1 < nil is nonsense so that's an error.

Since the error message starts with "Error Occured - " we know it must be coming from your try function error handler. This makes sense. You call:

try(refreshColors, function(e)
    print("Error Occured - "..e)
end)

try then invokes:

pcall(f)

where f is refreshColours. This invokes refreshColours without any arguments, i.e. all the arguments are initialised to nil. Of course, invoking refreshColouts with a nil value will naturally attempt to compare 1 (ccnt) to nil (yellowEndIndex)!

You probably want to modify your try function like so:

function try(f, catch_f, ...)
    local status, exception = pcall(f, unpack(arg))
    if not status then
        catch_f(exception)
    end
end

So you can call it like:

try(refreshColours, function(e)
    print("Error Occured - "..e)
end), 1, 2, 3);

To pass 1, 2 and 3 in as arguments to refreshColours.

like image 150
Martin Avatar answered Jan 03 '23 14:01

Martin


Is the error happening because you are calling:

try(refreshColors, function(e) print("Error Occured - "..e) end)

and, the refreshColors has no parameters so that it is indeed nil?

like image 38
Rich Avatar answered Jan 03 '23 15:01

Rich