如何让 lua 在 while true 循环中停止 if 循环?

Posted

技术标签:

【中文标题】如何让 lua 在 while true 循环中停止 if 循环?【英文标题】:How would I make a lua stop an if loop inside a while true loop? 【发布时间】:2016-10-07 18:04:22 【问题描述】:

这是一个很难问的问题,因为我不可能将所有内容都放入一个问题中,但我可以解释这个问题。我的游戏逻辑/游戏脚本本质上是:

function game()
-- stuff
end

while true do
    while players < 2 do
     -- tell player to invite more players and all that jazz
    end

    if players >= 2 then
       game()
    end
end

(这只是伪代码,为了简单起见,我忽略了诸如 wait() 和 Roblox API 之类的东西,因为这个想法仍然相同,但我认为这个问题对于一般编程来说已经足够笼统了)

现在,在我的“游戏”功能中,当玩家准备好(即不在菜单中等)时,它会将所有准备好的玩家传送到游戏所在的位置。不幸的是,由于 'game()' 一直在运行,玩家不断地被传送一次又一次,并且不会停止。我不确定如何制作,即使“game()”不断运行,它也只会传送一次。

以下是无需了解 Roblox API 即可简单解释的传送代码:

if #ready >= 2 then -- if the players in the list 'ready' (the players that are ready to start the game) 
    print(player.Name .. " moved") -- show which player is moved
    player:MoveTo(--place where the game is)) -- actually move the player
end

问题在于,由于 'game()' 一直在运行,玩家会不断地移动到游戏所在的位置(使他们无法移动)。在所有玩家都被移动后,我如何让 Lua 停止移动玩家?我尝试使用 for 循环,但由于“游戏()”被重复,因此也不断重复。我希望任何熟悉 Lua 的人都能理解这一点。

【问题讨论】:

你能在game() 通话后将break 退出循环吗? @itdoesntwork 如果我使用 break 那么只会移动 1 个玩家。 然后在玩家被移动时标记玩家,只移动未标记的玩家? 【参考方案1】:

在我看来,您希望维护两个列表:当前播放和希望播放。

我不确定您的具体逻辑是什么(人们可以加入正在进行的游戏吗?),但基本的想法是您只在希望玩的玩家列表中运行游戏,不是当前正在玩的玩家。

【讨论】:

以上是关于如何让 lua 在 while true 循环中停止 if 循环?的主要内容,如果未能解决你的问题,请参考以下文章

Lua 循环

Lua学习五----------Lua循环

lua如何让循环运行慢一点

while true 如何退出循环

使用“while (true) ...”有啥意义?

Lua学习总结二