Coroutine (协程)

协程是一种编程工具,它允许你在某些点暂停和恢复函数。与正常的函数执行不同,协程在指定的暂停点停止,并在稍后继续。这一特性对于管理需要随着时间发生而不停止整个程序的任务非常有用。
描述
Yield (暂停)在协程中使用的操作,用于暂停其执行,允许其他代码运行。它会临时停止协程并保存其状态。
Resume (恢复)从协程最后一次暂停的地方重新开始执行的操作,继续执行。
Status (状态)用于检查协程当前状态的函数,例如它是暂停、运行,还是已经结束(完成)。
Wrap (包装)一个包装函数,当调用时,它将恢复特定的协程,并且只返回暂停的值。

示例: Coroutine (协程)

local function countingCoroutine()
	for i = 1, 3 do  -- Count from 1 to 3
		coroutine.yield("Count: " .. i)  -- Yield the count value
	end
	return "Counting completed."  -- Return a final message when done
end

-- Create the coroutine from the function
local co = coroutine.create(countingCoroutine)

-- Start the coroutine and check the status and results at each step
print("Starting coroutine...")
print("Status before start:", coroutine.status(co))  -- Initially, status should be 'suspended'

local success, result = coroutine.resume(co)  -- Resume for the first count
print(success, result)  -- Should print true, "Count: 1"
print("Status after first count:", coroutine.status(co))  -- Should still be 'suspended'

success, result = coroutine.resume(co)  -- Resume for the second count
print(success, result)  -- Should print true, "Count: 2"
print("Status after second count:", coroutine.status(co))  -- Should still be 'suspended'

success, result = coroutine.resume(co)  -- Resume for the third count
print(success, result)  -- Should print true, "Count: 3"
print("Status after third count:", coroutine.status(co))  -- Should still be 'suspended'

success, result = coroutine.resume(co)  -- Resume for the final return
print(success, result)  -- Should print true, "Counting completed."
print("Status after completion:", coroutine.status(co))  -- Should now be 'dead'

-- Check status after completion to confirm no further actions can be taken
success, result = coroutine.resume(co)
print(success, result)  -- Should print false and possibly an error message
print("Status after attempting to resume a completed coroutine:", coroutine.status(co))  -- Should be 'dead'
Image 1
Roblox Studio

示例: 使用 coroutine.wrap (包装)

local function countToThree()
	for i = 1, 3 do
		coroutine.yield("Count: " .. i)  -- Yield with a return value
	end
	return "Counting completed."  -- Return a final message when done
end

local wrappedCoroutine = coroutine.wrap(countToThree)

print("Starting coroutine...")
local result
result = wrappedCoroutine()  -- Executes and yields "Count: 1"
print(result)  -- Prints "Count: 1"
result = wrappedCoroutine()  -- Resumes and yields "Count: 2"
print(result)  -- Prints "Count: 2"
result = wrappedCoroutine()  -- Resumes and yields "Count: 3"
print(result)  -- Prints "Count: 3"
result = wrappedCoroutine()  -- Ends the counting, returns "Counting completed."
print(result)  -- Prints "Counting completed."
result = wrappedCoroutine()  -- Error
Image 1
Roblox Studio

如果您觉得本教程对您有帮助,并且愿意支持我的工作,请考虑请我喝杯咖啡。

非常感谢您的支持!

请我喝咖啡