Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Referencing variables with strings?

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?

4 comments

0

I'm not sure what you're trying to do. What do arrays have to do with it? Strings cannot define values?

0

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"?

0

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?

0

The second of the two.

2 answers

✓ Accepted answer

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

0

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)."

1

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.

1

Yeah, I asked for something that isn't roblox-specific. thanks anyways

0

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.