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