Lua - error "try to compare a number with zero"
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 refreshColors () is called, it throws an exception and the error message "Error Occured - trial.lua: 11: Attempting to compare a number to nil" appears. Why is an exception thrown when there are no such comparisons in the refreshColors () function?
The error is listed on line 11, which means:
if ccnt < yellowEndIndex then
There your comparison with a number. We know that ccnt is a number (it's initialized at the beginning of the loop), so yellowEndIndex must be zero. 1 <nil is stupid, so it's a mistake.
Since the error message starts with "Error Occured", we know that it should come from the error handler of the try function. It makes sense. You are calling:
try(refreshColors, function(e)
print("Error Occured - "..e)
end)
try then calls:
pcall(f)
where f is refreshColours. This calls refreshColours without any arguments, i.e. All arguments are zero-initialized. Of course, calling refreshColouts with a null value will naturally try to compare 1 (ccnt) with nil (yellowEndIndex)!
You probably want to change your try function like this:
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 this:
try(refreshColours, function(e)
print("Error Occured - "..e)
end), 1, 2, 3);
To pass 1, 2 and 3 as arguments to refreshColours.
An error occured because you are calling:
try (refreshColors, function (e) print ("Error Occured -" .. e) end)
and refreshColors has no parameters so it really is zero?