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)

运行结果如下:

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值