Roblox 通過引入 task 庫更新了處理異步任務的最佳實踐。與較早的 spawn、delay 和 wait 函數相比,task 庫提供了一種更簡潔、更高效的方式來處理後台任務。task 庫包括 task.spawn, task.delay 和 task.wait 等方法,旨在更可靠並提供更好的性能。
| 操作 | 詳情 |
|---|---|
| task.spawn | task.spawn 用於異步運行函數而不阻塞調用者。 |
| task.delay | task.delay 用於在指定的延遲後執行函數,允許創建定時或延遲的操作而不阻塞其他操作。 |
| task.wait | task.wait 用於暫停當前任務指定的時間段。 |
task.spawn
local function doBackgroundTask()
print("Background task started")
for i = 1, 10 do
print("Processing step " .. i)
wait(1) -- Simulate some processing delay
end
print("Background task completed")
end
print("Main script execution")
task.spawn(doBackgroundTask)
print("Main script continues immediately after launching background task")Roblox Studio
task.delay
local function delayedTask()
print("Delayed task executed after 5 seconds")
end
print("Main script execution")
task.delay(5, delayedTask) -- Delay execution of delayedTask by 5 seconds
print("Main script continues immediately after scheduling delayed task")Roblox Studio
task.wait
local function waitForSomeTime()
print("Wait starting")
task.wait(5) -- Pauses this function, not the entire script, for 5 seconds
print("Wait ended after 5 seconds")
end
print("Main script execution")
task.spawn(waitForSomeTime)
print("Main script continues immediately, while waitForSomeTime pauses internally")Roblox Studio


