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

How to set a string equal to a local variable?

Asked by 3 years ago
Edited 3 years ago

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

Log in to vote
1
Answered by
Speedmask 661 Moderation Voter
3 years ago
Edited 3 years ago

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

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 imKirda 4491 — 3y
0
Thank you for the answers! I appreciate you both for taking time out of your days to help! BunnyFilms1 297 — 3y
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 :)  Speedmask 661 — 3y
Ad

Answer this question