比较多个变量

时间:2014-11-13 21:04:25

标签: variables lua compare

我有几个带有2个参数的变量,我想将一个值与它们进行比较,并在一段时间内修改那些相同的值,而没有写出If mynumber == x then x = ("NewValue") elseif mynumber == y then .......的所有可能性,因为我有要检查的很多变量。 例如:

x = 5 and ("Five")

y = 2 and ("Two")

z = 10 and ("Ten")

mynumber = io.read()

现在检查所有变量是否等于mynumber,并将那些(这些)变量更改为XXX

那么,你知道一种方法吗?

1 个答案:

答案 0 :(得分:3)

使用表格:

local lookup = {
    foo = "bar",
    bar = "baz",
    baz = "foo",
    ["some thing"] = "other thing",
}

local x = "foo"
x = lookup[x]

如果您尝试将数字中的单词转换为数字:

local lookup = {
    One = 1,
    Two = 2,
    Three = 3,
    -- Continue on for however long you need to
}

local x = "Two"
print(lookup[x]) -- Prints 2

local y = 3
print(lookup[y]) -- Prints nil, the number 3 isn't in the table

-- Better:
print(lookup[x] or x) -- Prints 2, as there was a truthy entry in lookup for x
print(lookup[y] or y) -- Prints 3; there wasn't a truthy entry in lookup for y, but y is truthy so that's used.

这比一个巨大的if-else链更实用,但对于更大的数字仍然很麻烦。如果您需要支持这些内容,则可能需要为每个数字(例如"Thirty Two"{"Thirty", "Two"})分割单词。