如果后面跟着的 elseif 在第一个 if 后面被忽略。

我正试图在一个游戏中使用此函数,但是我遇到了问题。

基本上所有这些容器函数都是正确的,问题在于lua本身。

唯一的问题是第一个if完成后,最后两个elseif被忽略了。

函数将弹药从from的容器提取到to的容器中

function withdrawAmmo(from, to)
    local ammoCount = Container(to):ItemCount(ammoID) + Self.Ammo().count
    print("Current Ammo : " .. ammoCount)
    local last = Container.GetLast()
    Walker.Stop()
    Self.OpenDepot()
    last:UseItem(from, true)
    print(" Ammo in this backpack : " .. last:ItemCount(ammoID))
    while last:ItemCount(ammoID) > 0 or ammoCount < maxAmmo do
        last:MoveItemToContainer(0, to, 0, 100)
        wait(800, 1200)
    end
    if ammoCount < maxAmmo then
        EnoughAmmo = false
        repeat
            print "Trying to find more ammo"
            for spot = last:ItemCount() - 1, 0, -1 do
                if Item.isContainer(last:GetItemData(spot).id) then
                    last:UseItem(spot, true)
                    wait(400, 800)
                    break
                end
            end
            last:MoveItemToContainer(0, to, 0, 100)
            wait(800, 1200)
        until ammoCount >= maxAmmo or not Container.GetLast():isFull()
    elseif ammoCount >= maxAmmo then EnoughAmmo = true
        print("Enough ammo, continuing")
        Walker.Start()
    elseif not EnoughAmmo then
        print("You don't have enough ammo!, stoping script...")
        Walker.Stop()
    end
end

Walker.Start()继续脚本,在第一个if完成后,脚本以某种方式继续,但不会打印“You don't have enough ammo!, stoping script...”或“Enough ammo, continuing”。

点赞
用户2319844
用户2319844

您对 if-elseif 结构的作用有一个根本的误解。

它只会执行 一个 条件下的代码。仅当第一个条件为 false 时,才会测试后续的条件。一旦找到一个 true 的条件,它将执行该条件下的代码,然后转到 end 后的代码。

让我解释一下,使用一个例子。您有一个看起来像这样的 if-elseif 块:

if y = z then
    print "y and z are equal (if)"
elseif y = z then
    print "y and z are equal (elseif)"
end

如果 y = 2 并且 z = 2 。当您的程序到达 if-elseif 块时,它将测试第一个条件(if y = z)。如果它是 true,它将执行块中的任何内容。然后它将转到 end 之后的任何内容。第二个条件(elseif y = z)永远不会被测试,因为第一个条件为真,并且第二个 print 语句永远不会被执行。

以下是另一个例子,但此程序将打印 y and z are equal 两次:

if y = z then
    print "y and z are equal"
end

if y = z then
    print "y and z are equal"
end

您应该做的

因为您希望测试第二个和第三个条件,所以您需要将它们分别放到单独的 if 块中,如下所示:

if ammoCount < maxAmmo then
    // 做些事情
end

if ammoCount >= maxAmmo then
    EnoughAmmo = true
    print("Enough ammo, continuing")
    Walker.Start()
end

if not EnoughAmmo then
    print("You don't have enough ammo!, stoping script...")
    Walker.Stop()
end
2014-04-13 22:13:43