简体   繁体   中英

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?

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 , ie 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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM