检查所有陈述是否都是假的?

时间:2013-01-17 10:33:35

标签: lua corona

只有在多个语句为假时才能执行一行代码吗?

我有一个清单:

inventory = {
    {"Images/Category 1/pistol1.png", false},
    {"Images/Category 1/machinePistol1.png", false},
    {"Images/Category 2/shotgun1.png", false},
    {"Images/Category 2/assaultRifle1.png", false},
    {"Images/Category 3/sniperRifle1.png", false},
    {"Images/Category 3/rocketLauncher1.png", false}
}

我想编写一个函数来执行一行代码,如果所有这些语句都是假的,但是如果其中一个是真的话,显然会执行其他操作。

1 个答案:

答案 0 :(得分:6)

您可以使用变量,并假设它是真的

local IsEverythingTrue = true

-- the **for** statement is a loop. It will allow us to operate
-- the same way on any number elements in inventory.
-- _,v stands for variables that we are going to read from inventory table
-- we can't do it directly, however; **ipairs** function will prepare it so
-- _ will hold numerical index of each element (1, 2, 3 and so on);
-- we don't use it, though, so I put in a placeholder name
-- v will hold every value, so your two-element table

for _,v in ipairs(inventory) do

    -- if any value of v[2] is false, break
    -- v[2] is equal to inventory[_][2]
    -- if not v[2] can be written as 
    -- *if value of v[2] isn't true*

    if not v[2] then
        -- in this case, after first non-true element has been found
        -- we know that not every one is true, or there is at least one false
        IsEverythingTrue = false
        break -- we don't have to check anything else
    end
end

然后在表达式中使用该变量

if IsEverythingTrue then
    -- do something
else
    -- do something else
end

如果您希望使用多个 falses执行它,请计算它们。在开头添加local falseCount = 0,并为break更改falseCount = falseCount + 1