情况调度器 |
|
这个调度器使用“条件”的概念。协程只有在它的条件为真时才会被调度。当协程第一次被调度时,它通常会被赋予一个“真”条件,并在下一个可用时隙中执行。然后,它可以在任何时候让出控制权,在让出时返回一个新的条件。如果没有返回这样的条件,协程将不会被重新调度。
预期像 `wait()` 或 `WalkTo()` 这样的辅助函数将包含返回适当条件的让出操作,而脚本编写者永远不必担心显式让出。结果是一个系统,在一定范围内,它按照你期望的方式工作。
代码可以在 Files:wiki_insecure/users/twrensch/play.lua 中找到。
以下是一个示例(也包含在上面的源文件中)
-- Wait is a function that tells the scheduler to
-- wait for some number of seconds before restarting
-- the script.
function wait(seconds, start)
local t = (start or os.clock()) + seconds
coroutine.yield(
function() return os.clock() >= t end)
end
-- Two pretty much identical functions that differ
-- only in the label they print and the amount of
-- time they wait between prints.
simsch.start(
function ()
for i=1,10 do
wait(1)
print("One ", i)
end
end)
simsch.start(
function ()
for i=1,10 do
wait(1.6)
print("Two ", i)
end
end)
-- Start it up
simsch.run()
我设想这在游戏中的脚本代理中很有用。例如,假设我正在为我的狗 Rover 写一个脚本。我想让它去我家,取回我的战斧,然后回来。一个脚本可能看起来像这样
function Rover:fetchAxe()
local location = whereAmI(self)
Rover:walkTo(self.home)
self:pickup(MyAxe)
Rover:walkTo(location)
self:drop()
end
在这里,`walkTo()` 函数将包含带有适当条件参数的让出操作,以处理路径和延迟时间。因此,效果是脚本将花费与操作所需的游戏和/或真实时间一样多的时间来执行,即走到家,然后回到它开始的地方。`walkTo()` 函数的一个简单版本可能只是等待与距离和代理速度相适应的时间
function Agent:walkTo(there)
local here = whereAmI(self)
local distance = here:distanceTo(there)
local arivalTime = now() + distance / self.speed
coroutine.yield(
function() return now() >= arivalTime end)
end