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

How to set a string equal to a local variable?

Hello! I am trying to figure out how to set a string value to be equal to a predefined local variable. Below is an example of what I am trying to accomplish:

local var2 = "Hmm"

local playerValue = 2

local chosenVar = "var"..playerValue  --This would ideally be equal to the local variable on line 1.
print(chosenVar) --Instead, it just prints "var2" because it is just a string.

Instead of it printing var2, how could I make it print the local variable of var2 which is "Hmm"

1 answer

✓ Accepted answer

you can’t. when you make a variable name, there’s no way to access it (generally, and even if you could, it’s not a good idea). they are simply there to help you read better :)

however, when the variable is part of a table it’s a different story. you can try something like MyVars = {“var2” = “Hmm”} and then use MyVars[a .. b] and that will work just fine.

notice how I said generally. in lua, all variables are stored in a global script table. you can get this with the function getfenv(). however, it's not a good idea to use for normal scripts, unless you are making some sort of script-manipulating plugin, and just makes things confusing

3 comments

2

Good solution, however, it's still possible to do exactly what Bunny wants, not saying it's good practice or anything but using getfenv and globals it works : https://pastebin.com/MbiHUFbM

0

Thank you for the answers! I appreciate you both for taking time out of your days to help!

0

I wasn't aware of that, I knew lua scripts had some sort of global directory and I thought about it when I made the post, but I brushed it off. I will edit my post, thanks :) 

This discussion is preserved as it was. New answers, comments, and votes are closed.