function Role:init(name) self.name = name; self.attackDelay = -10; end
function Role:attack(coroutine_) printf (self.name .. " attack") self.coroutine_ = coroutine_; self.attackDelay = 2; return coroutine.yield() end
function Role:update(dt) self.attackDelay = self.attackDelay - dt; if self.attackDelay <= 0 and self.attackDelay > -10 then -- 确保完成一次 self:attacked(); self.attackDelay = -10; end end
function Role:attacked() coroutine.resume(self.coroutine_) end
-- main.lua local Role = require("Role") local hero = setmetatable({} , {__index = Role}); local monster = setmetatable({} , {__index = Role}); hero:init("Hero"); monster:init("Monster");
function printf(...) print(os.clock() ,...) end
function love.load() local coroutine_ local round = 5; coroutine_ = coroutine.create(function () printf "fight begin" for i=1, round do printf("round " , i, " begin")
hero:attack(coroutine_); monster:attack(coroutine_); printf("round " , i, " end") print("---------------------") end printf "fight end" end)
coroutine.resume(coroutine_) end
function love.update(dt) monster:update(dt); hero:update(dt); end