Lua中未定义的标签



以下代码有未定义的标签room3。如何修复此错误?

function room1 ()
    local move = io.read()
    if move == "south" then goto room3
    elseif move == "east" then return room2()
    else
        print("invalid move")
        return room1()   -- stay in the same room
    end
end
function room2 ()
    local move = io.read()
    if move == "south" then return room4()
    elseif move == "west" then return room1()
    else
        print("invalid move")
        return room2()
    end
end
::room3:: 
do
    local move = io.read()
    if move == "north" then return room1()
    elseif move == "east" then return room4()
    else
        print("invalid move")
        goto room3
    end
end
function room4 ()
    print("congratulations!")
end
-- We start the game with a call to the initial room:
room1()

另一方面,这个代码运行得很好:

goto room1
::room1:: do
    local move = io.read()
    if move == "south" then goto room3
    elseif move == "east" then return room2()
    else
        print("invalid move")
        goto room1
    end
end
::room2:: do
    local move = io.read()
    if move == "south" then goto room4
    elseif move == "wast" then goto room1
    else
        print("invalid move")
        return room2()
    end
end
::room3:: do
    local move = io.read()
    if move == "north" then goto room1
    elseif move == "east" then goto room4
    else
        print("invalid move")
        goto room3
    end
end
::room4:: do
    print "Congratulations, you won!"
end

room3room1()的范围内不可见。

来自Lua参考:

标签在定义它的整个块中可见,除外在嵌套块中,其中定义了具有相同名称的标签,并且嵌套函数内部。goto可以跳转到任何可见标签,只要因为它不进入局部变量的范围。

因此,您不能使用goto跳转到一个函数或从一个函数跳出来。不能跳转到函数中,因为标签在函数内部,所以在外部是不可见的。你不能跳出函数,因为你不能从函数内部看到外部标签。

我宁愿使用递归函数调用。我认为您没有理由实施与其他房间不同的room3

function room3()
    local move = io.read()
    if move == "north" then return room1()
    elseif move == "east" then return room4()
    else
        print("invalid move")
        return room3()
    end
end

还请注意,当您在room1中往东时,您的工作示例将导致错误,因为未定义function room2

最新更新