我目前正在使用Roblox(使用Lua)进行游戏.它基本上由几个小游戏组成.在每轮开始时,游戏中的所有玩家都被放入桌子并被传送到一个区域.这是协程开始发挥作用的地方.随着回合的进行,我
对不起,如果我没有正确描述问题,但协程将不会产生.我之前没有使用过协同程序,所以我可能试图以错误的方式使用它.我知道你们大多数人都不熟悉Roblox,但是Lua的语法是一样的.
有人可以给我一个例子,说明如何结束循环协程吗?
currentPlayers = {}
roundTime = 60
local lookForWinners = coroutine.create(function()
while coroutine.running do
wait(1)
for i, v in pairs(currentPlayers) do
if v.Character.Humanoid.Health <= 0 then
table.remove(currentPlayers, v)
end
end
end
end)
while wait() do
repeat display("Two or more players need to be in the game.", 1) until #_G.plrs > 1 --Ignore, just checks if two+ players are in game.
display("Picking a map...", 3) pickMap()
teleport(0, 500, 0)
coroutine.resume(lookForWinners)
wait(roundTime)
print("Round over")
coroutine.yield(lookForWinners)
end
Lua是一种单线程语言.协同程序不会导致函数并行执行.
协同程序实际上只是一种方法来创建一个可以暂停自己执行的函数(使用coroutine.yield),可以从外部恢复(使用coroutine.resume). There is no “coroutine.running”:在任何给定时间只有一条线“正在运行”.
如果Roblox意味着您使用wait()跳出Lua线程,您可以将其写为一系列循环来检查它们的条件,然后调用wait():
local currentPlayers={}
local roundTime = 60
while #_G.plrs > 1 do
display("Two or more players need to be in the game.", 1)
wait()
end
display("Picking a map...", 3) pickMap()
teleport(0, 500, 0)
for i=0, roundTime do
for i, v in pairs(currentPlayers) do
if v.Character.Humanoid.Health <= 0 then
table.remove(currentPlayers, v)
end
end
wait(1)
end
print("Round over")
但是,这是糟糕的代码. (每当你编写代码时,让其中带有“wait”函数的循环用于指示某些内容正在被错误地完成.)你应该使用Roblox的Events来处理游戏的逻辑.
>检查游戏是否应该仅在玩家数量发生变化时启动.
>只有在Humanoid的健康状况发生变化时才会“寻找胜利者”(HealthChanged事件).
>在某种计时器或间隔上运行计时器(不要忘记,一旦有人赢了,你可能想要提前结束你的游戏).
事件比繁忙的循环有许多优点;最明显的一点是,当他们检查的东西发生时,你的支票就会发生,而不是以后.
