Lua学习笔记-习题9.3

题目:

Implement a transfer function in Lua. If you think about resume-yield as similar to call-return, a transfer would be like a goto: it suspends the running coroutine and resumes any other coroutine, given as argument.
使用例子如下:
下面的例子,通过resume-yield实现goto功能,类似走迷宫,goto到指定的threads,本文指定为threads[4]则显示结束。

代码:

function transfer(co)
    coroutine.yield(co)
end

threads = {}

threads[1] = coroutine.create(function()
    while true do
        local move = io.read()
        if move == "south" then
            transfer(threads[3])
        elseif move == "east" then
            transfer(threads[2])
        else
            print("Invalid move.")
        end
    end
end)

threads[2] = coroutine.create(function()
    while true do
        local move = io.read()
        if move == "south" then
            transfer(threads[4])
        elseif move == "west" then
            transfer(threads[1])
        else
            print("Invalid move.")
        end
    end
end)

threads[3] = coroutine.create(function()
    while true do
        local move = io.read()
        if move == "north" then
            transfer(threads[1])
        elseif move == "east" then
            transfer(threads[4])
        else
            print("Invalid move.")
        end
    end
end)

threads[4] = coroutine.create(function()
    print("Congretualtions, you won!")
end)

function dispatch(i)
    local nextCo = threads[i]
    while true do
        local status, to = coroutine.resume(nextCo)
        if not status then
            print(to)
            break
        end
        if coroutine.status(nextCo) == "dead" then
            break
        end
        nextCo = to
    end
end

dispatch(1)

运行结果如下:

Lua学习笔记-习题9.3_第1张图片

你可能感兴趣的:(lua)