既然已经出现了一些意见,询问如何实现wait
功能,这将使deft_code
的例子的工作,我决定写一个可能的实现。总的想法是我们有一个调度程序和一系列协程,调度程序决定何时在控制wait
调用后放弃对协程的控制。这是可取的,因为它使得异步代码易读并易于推理。
这只是协程的一种可能的用法,它们是一个更一般的抽象工具,可用于许多不同的目的(例如编写迭代器和生成器,编写有状态的流处理对象(例如,解析器),实现异常和延续等)。
第一:调度定义:
local function make_scheduler()
local script_container = {}
return {
continue_script = function(frame, script_thread)
if script_container[frame] == nil then
script_container[frame] = {}
end
table.insert(script_container[frame],script_thread)
end,
run = function(frame_number, game_control)
if script_container[frame_number] ~= nil then
local i = 1
--recheck length every time, to allow coroutine to resume on
--the same frame
local scripts = script_container[frame_number]
while i <= #scripts do
local success, msg =
coroutine.resume(scripts[i], game_control)
if not success then error(msg) end
i = i + 1
end
end
end
}
end
现在,初始化世界:
local fps = 60
local frame_number = 1
local scheduler = make_scheduler()
scheduler.continue_script(frame_number, coroutine.create(function(game_control)
while true do
--instead of passing game_control as a parameter, we could
--have equivalently put these values in _ENV.
game_control.wait(game_control.seconds(5))
game_control.start_eruption_volcano()
game_control.wait(game_control.frames(10))
s = game_control.play("rumble_sound")
game_control.wait(game_control.end_of(s))
game_control.start_camera_shake()
-- more stuff
game_control.wait(game_control.minutes(2))
end
end))
的(虚拟)接口的游戏:
local game_control = {
seconds = function(num)
return math.floor(num*fps)
end,
minutes = function(num)
return math.floor(num*fps*60)
end,
frames = function(num) return num end,
end_of = function(sound)
return sound.start+sound.duration-frame_number
end,
wait = function(frames_to_wait_for)
scheduler.continue_script(
frame_number+math.floor(frames_to_wait_for),
coroutine.running())
coroutine.yield()
end,
start_eruption_volcano = function()
--obviously in a real game, this could
--affect some datastructure in a non-immediate way
print(frame_number..": The volcano is erupting, BOOM!")
end,
start_camera_shake = function()
print(frame_number..": SHAKY!")
end,
play = function(soundname)
print(frame_number..": Playing: "..soundname)
return {name = soundname, start = frame_number, duration = 30}
end
}
而且游戏圈:
while true do
scheduler.run(frame_number,game_control)
frame_number = frame_number+1
end
协程不是线程。它们是线程的,因为它们是独立的执行环境,但是你的程序是调度程序,并且它们不是抢占式的。我会添加一个完整的答案,但我的Lua是生锈的,所以我不能提供任何代码示例... – 2011-02-26 17:09:26