【Lua】题目小练3
-- 题目 1:协程的基本创建与运行
-- 要求:
-- 创建一个协程函数 countDown(n),每次调用 coroutine.resume 时输出 n 到 1。
-- 每次输出一个数字后 coroutine.yield()。
function countDown(n)while n > 0 docoroutine.yield(n)n = n - 1end endlocal co = coroutine.create(function() countDown(5) end) while true dolocal success, value = coroutine.resume(co)if not success or value == nil then break endprint(value) en
-- 题目 2:传递参数给协程
-- 要求:
-- 创建一个协程函数 echo(),每次 resume 时打印传递进来的值。
function echo()while true dolocal _, val = coroutine.yield() -- 等待传入值print("接收到传入的值为:" .. tostring(val))end endlocal 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 docoroutine.yield(i)endend) endfor i in range(1, 5, 1) doprint(i) end
-- 题目 4:实现一个有限状态机
-- 要求:
-- 使用协程模拟一个状态机,有三个状态:Idle → Working → Done,每次 resume 转换一次状态并输出当前状态。
function stateMachine()local states = { "Idle", "Working", "Done" }local index = 1while true docoroutine.yield(states[index])index = index % #states + 1end endlocal co = coroutine.create(stateMachine) for _ = 1, 6 dolocal _, state = coroutine.resume(co)print(state) end
-- 题目 5:斐波那契生成器
-- 要求:
-- 使用协程实现一个无限斐波那契数列生成器(每次 resume 输出一个斐波那契数)。
function fibonacci()local a, b = 0, 1while true docoroutine.yield(b)a, b = b, a + bend endlocal co = coroutine.create(fibonacci) for _ = 1, 10 dolocal _, val = coroutine.resume(co)print(val) end