Reputation: 25
Basically I have something like below.. Feedback from the user is in the form of a string. "CONST_ME_NONE"
Is there any way to convert "CONST_ME_NONE" into the variable name CONST_ME_NONE?
local CONST_ME_NONE = 0
local CONST_ME_DRAWBLOOD = 17
local CONST_ME_LOSEENERGY = 24
local effects = {CONST_ME_NONE, CONST_ME_DRAWBLOOD, CONST_ME_LOSEENERGY}
local user_input = "CONST_ME_NONE"
user_input = -- do something to convert string to variable name
for i = 1, #effects do
if effects[i] == user_input then
-- do something
break
end
end
Upvotes: 1
Views: 714
Reputation: 5564
Since the names you're working with must match user input, and table keys can be strings, it will be much easier to use those names as table keys rather than variables.
local effects = {
CONST_ME_NONE = 0,
CONST_ME_DRAWBLOOD = 17,
CONST_ME_LOSEENERGY = 24,
}
local user_input = "CONST_ME_NONE"
if effects[user_input] ~= nil then
-- do something
end
Upvotes: 3
Reputation: 616
you can convert a string with the name of a variable into a real variable using load()
:
load("return string")
example:
print(variable)
eh equals to:
print(load("return variable")())
in your case, instead of
if effects[i] == user_input then
use:
if effects[i] == load("return user_input")() then
you can also check if the method works with print:
print(load("return user_input")())
Upvotes: 0