I was wondering if there was any way to reference a variable with a string, aside from having the string define a value in an array. Additionally, I want to be able to do it without roblox-specific methods, so no "FindFirstChild()" either. Any ideas?
Referencing variables with strings?
2 answers
It sounds like you might be using Lua 5.2 (which is not Roblox). In that case, your solution would look like this:
test=5
print(_ENV["test"])
which you can test here.
otherwise adark's Lua 5.1 solution will work in Roblox.
As long as the variable is not declared using the keyword local. You can use getfenv to get a table of all the global variables in the current script:
var1 = 23
local var2 = 57
print(getfenv()["var1"]) -- 23
print(getfenv()["var2"]) -- nil
4 comments
I tested it myself, and though all variables are global, when I attempt to reference a variable with getfenv() it returns the error "attempt to call global 'getfenv'(a nil value)."
In that case it sounds like you aren't using Roblox and you're in some other program that is running Lua 5.2, which no longer uses getfenv or setfenv and instead uses a new mechanic for handling function environments.
Yeah, I asked for something that isn't roblox-specific. thanks anyways
getfenv() isn't ROBLOX-specific, it's Lua 5.1-specific.
This discussion is preserved as it was. New answers, comments, and votes are closed.

4 comments
I'm not sure what you're trying to do. What do arrays have to do with it? Strings cannot define values?
Referencing variables with strings. For example, say var1 is a variable in my script. Is there any way I can use a string to reference it with the corresponding string, being "var1"?
What do you mean by "reference it?" do you mean like having a string which contains the name of a variable and have it replace it with the actual variable? or just access the variable through its string name like indexing it from the function environment?
The second of the two.