初学 Lua 循环函数。

我刚开始学习lua,昨晚刚开始。我编写了一个游戏脚本,但发现它无法操作。

我的脚本中有三个函数,它们是:**function shoot()function pickplayer()** 和 **function drinkwater()**。

  1. 不间断地运行 function shoot() 35秒。
  2. 然后在 function shoot() 完成后立即运行 **function pickplayer()**。
  3. 重复步骤1和步骤2三次。
  4. 然后运行 **function drinkwater()**。

我已经单独运行了这三个函数,并且它们都可以正常工作,但是当我将它们组合在一起时,脚本就无法按照我的要求运行。因为它不能在跳转到其他函数之前不间断地运行 function shoot() 35秒。

如果你们能帮我指出问题所在,我将非常感激,这样我就可以继续前进了。

请参阅以下脚本:

点赞
用户869951
用户869951

所有的 touchDown,touchUp 和 sleep 都是噪音,这里的问题是协程的“调度”。基本上你有这样的东西:

function condition1() return true end -- 用于测试
function condition2() return true end -- 用于测试

function shoot()
    while true do
        -- 做一些事情,然后:
        coroutine.yield()
    end
end

function pickplayer()
    while true do
        if condition1() then
            -- 做一些事情,然后:
            mSleep(1500)
        end
        mSleep(500)
        coroutine.yield()
    end
end

function drinkwater()
    while true do
        if condition2() then
            -- 做一些事情,然后:
            mSleep(9000)
        end
        coroutine.yield()
    end
end

function main()
    co1 = coroutine.create(shoot)
    co2 = coroutine.create(pickplayer)
    co3 = coroutine.create(drinkwater)

    while true do
        local timeToRun = 35000
        local initialTime = os.time()
        local timeElasped=os.difftime(os.time(), initialTime)
        while timeElasped < timeToRun do
            coroutine.resume(co1)
            timeElasped =os.difftime(os.time(), initialTime)
            mSleep(2000)
            coroutine.resume(co2)
            coroutine.resume(co3)
        end
    end
end

上面的代码会做这些事情:

  1. 运行函数 shoot()
  2. 然后运行函数 pickplayer()
  3. 然后运行函数 drinkwater()
  4. 重复步骤 1 到 3。

但是你说你想要实现这个:

  1. 连续运行函数 shoot() 35 秒
  2. 然后运行函数 pickplayer()
  3. 重复步骤 1 和 2 三次
  4. 然后运行函数 drinkwater()

这将需要你的 main 函数做以下操作(注意,repeat-until 在这里比 while-do-end 更好看):

function main()
    co1 = coroutine.create(shoot)
    co2 = coroutine.create(pickplayer)
    co3 = coroutine.create(drinkwater)

    for i=1,3 do -- 做以下操作 3 次:
        -- 连续运行 shoot() 35 秒
        local timeToRun = 35000
        local initialTime = os.time()
        local timeElasped = 0
        repeat
            coroutine.resume(co1)
            timeElasped = os.difftime(os.time(), initialTime)
        until timeElasped < timeToRun

        -- mSleep(2000): 不需要这个

        coroutine.resume(co2) -- pickplayer
    end
    coroutine.resume(co3)
end
2014-05-23 22:06:19