我希望它只循环一次

时间:2021-01-26 08:34:37

标签: loops lua

我有循环问题。我希望它只循环一次,但它会不断打印。如果我确实返回,脚本将停止,我不希望那样,因为我必须重新启动服务器,脚本总是会被触发。知道如何解决这个问题吗?

    local hit = GetPedLastDamageBone(ped)
    local chance = math.random(0,10) 
    local ped = PlayerPedId()
    while true do 
        Wait(0)
        if GetEntityHealth(ped) > 0 then
            if DMGByWeapon then
                if hit == 45454 or 33646 then
                    print("Foot")
                end
            end
        end
    end

1 个答案:

答案 0 :(得分:2)

<块引用>

我希望它只循环一次

loop 的全部目的是多次执行代码块。

所以如果你只想循环一次,你就不需要循环。只需从代码中删除循环即可。

local hit = GetPedLastDamageBone(ped)
local chance = math.random(0,10) 
local ped = PlayerPedId()
Wait(0)
if GetEntityHealth(ped) > 0 then
  if DMGByWeapon then
    if hit == 45454 or 33646 then
      print("Foot")
    end
  end
end
<块引用>

但它一直在打印。

while true do end

是一个无限循环。条件始终为真且永远不会改变,因此循环将永远运行。

<块引用>

如果我真的回来了,脚本就会停止

您的脚本文件被编译为一个块。 Chunks 被视为匿名函数的主体。 return 将终止该函数并因此终止您的脚本,除非您在该块的函数定义中使用它。

如果您想提前停止循环,请使用 break

请阅读 Lua 手册并做一个初学者教程。

if hit == 45454 or 33646 then
   print("Foot")
end

相当于

if hit == 45454 or true then
   print("Foot")
end

简化为

if true then
  print("Foot")
end

或者干脆

print("Foot")

任何既不是 nil 也不是 false 的值是 true 所以 33646 在逻辑上是 trueor 使用 true 进行任何操作都会产生 true

条件总是满足的 if 语句毫无意义。

您可以简单地使用逻辑运算符组合条件,而不是嵌套多个 if 语句。

所以代替

if GetEntityHealth(ped) > 0 then
  if DMGByWeapon then
    if hit == 45454 or 33646 then
      print("Foot")
    end
  end
end

你可以写

if GetEntityHealth(ped) > 0 and DMGByWeapon then
  print("Foot")
end

但如果你真的想使用 if 语句,你需要修正条件:

if hit == 45454 or hit == 33646 then
  print("Foot")
end