Variables 比较多个变量

Variables 比较多个变量,variables,lua,compare,Variables,Lua,Compare,我有几个带有两个参数的变量,我想将一个值与它们进行比较,并一次性修改那些相等的变量,而不必编写所有可能的如果mynumber==x那么x=(“NewValue”)elseif mynumber==y那么……,因为我有很多变量要检查。 例如: 现在检查所有变量中是否有一个等于mynumber,并将该变量更改为XXX 那么,你知道这样做的方法吗?使用表格: local lookup = { foo = "bar", bar = "baz", baz = "foo",

我有几个带有两个参数的变量,我想将一个值与它们进行比较,并一次性修改那些相等的变量,而不必编写所有可能的
如果mynumber==x那么x=(“NewValue”)elseif mynumber==y那么……
,因为我有很多变量要检查。 例如:

现在检查所有变量中是否有一个等于mynumber,并将该变量更改为XXX

那么,你知道这样做的方法吗?

使用表格:

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连锁店更实用,但对于数量更大的连锁店来说仍然很麻烦。如果您需要支持这些,您可能需要为每个数字拆分单词(例如,
“三十二”
{“三十”,“二”}
)。

对不起,我不是有意的,我是这个网站的新手。我甚至没有看到变化。我只是在纠正一些错误,你为什么不发表评论?哦,我想你在编辑我的时候,所以你的比我的多。是的,就是这样。我只是添加了一个变量示例。谢谢你让这篇文章更具可读性(我们是这么说的吗?我是瑞士人,英语不是我的第一语言)是的,这是一个常见的短语。好吧,我试过这种方法,但我仍然不知道/理解如何更改等于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.