【Lua】题目小练3

发布于:2025-08-03 ⋅ 阅读:(10) ⋅ 点赞:(0)

-- 题目 1:协程的基本创建与运行

-- 要求:

-- 创建一个协程函数 countDown(n),每次调用 coroutine.resume 时输出 n 到 1。

-- 每次输出一个数字后 coroutine.yield()。

function countDown(n)
    while n > 0 do
        coroutine.yield(n)
        n = n - 1
    end
end

local co = coroutine.create(function() countDown(5) end)
while true do
    local success, value = coroutine.resume(co)
    if not success or value == nil then break end
    print(value)
en

-- 题目 2:传递参数给协程

-- 要求:

-- 创建一个协程函数 echo(),每次 resume 时打印传递进来的值。

function echo()
    while true do
        local _, val = coroutine.yield()  -- 等待传入值
        print("接收到传入的值为:" .. tostring(val))
    end
end

local co = coroutine.create(echo)
coroutine.resume(co)          -- 启动协程
coroutine.resume(co, "Hello")
coroutine.resume(co, "World")
coroutine.resume(co, "Again")

-- 题目 3:实现一个迭代器生成器

-- 要求:

-- 使用协程实现一个迭代器 range(start, stop, step),类似于 Python 中的 range()

function range(start, stop, step)
    return coroutine.wrap(function()
        for i = start, stop - 1, step do
            coroutine.yield(i)
        end
    end)
end

for i in range(1, 5, 1) do
    print(i)
end

-- 题目 4:实现一个有限状态机

-- 要求:

-- 使用协程模拟一个状态机,有三个状态:Idle → Working → Done,每次 resume 转换一次状态并输出当前状态。

function stateMachine()
    local states = { "Idle", "Working", "Done" }
    local index = 1
    while true do
        coroutine.yield(states[index])
        index = index % #states + 1
    end
end

local co = coroutine.create(stateMachine)
for _ = 1, 6 do
    local _, state = coroutine.resume(co)
    print(state)
end

 -- 题目 5:斐波那契生成器

-- 要求:

-- 使用协程实现一个无限斐波那契数列生成器(每次 resume 输出一个斐波那契数)。

function fibonacci()
    local a, b = 0, 1
    while true do
        coroutine.yield(b)
        a, b = b, a + b
    end
end

local co = coroutine.create(fibonacci)
for _ = 1, 10 do
    local _, val = coroutine.resume(co)
    print(val)
end