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