How do i reference a value in a script if i have the name of it in a string

I’ll let my example script talk for me. Because i can’t really describe it.

local Var1 = "what"
local Var2 = 12
local var3 = script.Parent

for i = 1, 1, 3 do
    print() --this is what i don't get... i can't just do ("Var"..i) because that won't reverence eg.: Var1
end

How can i do this? How do i reference with a string in a script?
Sorry i don’t know how to describe this exactly.

You could put all your variables into a table then use

for _,Var in pairs(tablename) do
    print(Var)
end
2 Likes

I will mark it as the solution. Good workaraound, but i still want to know how to reference with string.

I don’t believe there is a way, well actually now that I think of it i’m pretty sure

["Var1"] = "CoolString"

Is a valid syntax so maybe try that and see what happens

Edit: It’s not a valid Syntax i’m pretty sure there isn’t a way to do it

Sad… Eh, i guess i’ll do it that way. At least someone helped.

Tl;dr you can’t and shouldn’t

It is not possible to reference locals “dynamically” in ROBLOX Lua. It’s possible in regular Lua with the debug library, but you really need to know your stuff and it’s far slower than just using a table.

You can use getfenv() if you remove the locals:

Var1 = "what"
Var2 = 12
Var3 = script.Parent

for k,v in pairs(getfenv()) do
    print(k, v) -- prints "Var1", "what", "Var2" etc. and possibly a bunch of other stuff
end

Notice something? You’re reading from a table! The Vars are actually just being put in the global variables table.
A table is the right way to do this. Locals are not meant to be accessed the way you want to access them. If you want something like that, put them in a table.

local vars = {
	Var1 = "what",
	Var2 = 12,
	Var3 = script.Parent
}

for k,v in pairs(vars) do
    print(k, v) -- prints "Var1", "what", "Var2" etc. and nothing else
end
2 Likes