5
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])

refreshColors() 関数が呼び出されると、例外がスローされ、エラー メッセージは「エラーが発生しました - Trial.lua:11: number を nil と比較しようとしました」です。refreshColors() 関数にそのような比較がないのに例外が発生するのはなぜですか?

4

2 に答える 2

8

エラーは11行目にあります。これは、次のことを意味します。

if ccnt < yellowEndIndex then

数字との比較があります。ccntは数値(ループの開始時に初期化される)であることがわかっているため、yellowEndIndexはnilである必要があります。1 <nilはナンセンスなので、エラーです。

エラーメッセージは「ErrorOccured-」で始まるため、try関数のエラーハンドラから発生している必要があります。意味あり。あなたが呼ぶ:

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

次に、次を呼び出します。

pcall(f)

ここで、fはrefreshColoursです。これにより、引数なしでrefreshColoursが呼び出されます。つまり、すべての引数がnilに初期化されます。もちろん、nil値でrefreshColoutsを呼び出すと、当然、1(ccnt)とnil(yellowEndIndex)を比較しようとします。

おそらく、次のようにtry関数を変更する必要があります。

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

したがって、次のように呼び出すことができます。

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

1、2、3をrefreshColoursの引数として渡す。

于 2013-02-11T21:53:30.810 に答える
1

あなたが呼び出しているためにエラーが発生しています:

try(refreshColors, function(e) print("エラーが発生しました - "..e) end)

そして、refreshColors にはパラメーターがないため、実際には nil ですか?

于 2013-02-11T21:51:23.127 に答える