Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Referencing variables with strings?

Asked by 8 years ago

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?

0
I'm not sure what you're trying to do. What do arrays have to do with it? Strings cannot define values? 1waffle1 2908 — 8y
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"? aquathorn321 858 — 8y
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? 1waffle1 2908 — 8y
0
The second of the two. aquathorn321 858 — 8y

2 answers

Log in to vote
2
Answered by
1waffle1 2908 Trusted Badge of Merit Moderation Voter Community Moderator
8 years ago

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.

Ad
Log in to vote
3
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
8 years ago

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
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)." aquathorn321 858 — 8y
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. 1waffle1 2908 — 8y
1
Yeah, I asked for something that isn't roblox-specific. thanks anyways aquathorn321 858 — 8y
0
getfenv() isn't ROBLOX-specific, it's Lua 5.1-specific. adark 5487 — 8y

Answer this question