Reputation: 21
I have a several number of variables with 2 arguments, I would like to compare a value with them, and modify the ones who are equal all that in one time, without writing every possibility of If mynumber == x then x = ("NewValue") elseif mynumber == y then .......
because I have A LOT of variables to check.
Example:
x = 5 and ("Five")
y = 2 and ("Two")
z = 10 and ("Ten")
mynumber = io.read()
Now check within all variables if one equals to mynumber, and change that(these) variable(s) to XXX
So, do you know a way to do that ?
Upvotes: 2
Views: 301
Reputation: 26549
Use a table:
local lookup = {
foo = "bar",
bar = "baz",
baz = "foo",
["some thing"] = "other thing",
}
local x = "foo"
x = lookup[x]
If you're trying to convert words for numbers into numbers themselves:
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.
This is a bit more practical than a giant if-else chain, but can still be cumbersome for larger numbers. If you need to support those, you may need to split up the word for each digit (ex. "Thirty Two"
to {"Thirty", "Two"}
).
Upvotes: 3