Concatenate two strings to get the name of a variable

Let’s say I have 3 variables:

local VarX = 1
local VarY = 2
local VarZ = 3

How could I concatenate two strings together to get the name of the variable and then change the value of those variables from my two concatenated strings. For example:

local function concatStrings(key)
	"Var"..key = 5
end

concatStrings("X")
concatStrings("Y")
concatStrings("Z")

This obviously won’t work but how could I do something like this?

local VariableTable = {
    ["VarX"] = 1,
    ["VarY"] = 2,
    ["VarZ"] = 3
}

local function concatStrings(key)
    VariableTable["Var"..key] = 5
end

concatStrings("X")
concatStrings("Y")
concatStrings("Z")

what about this?

1 Like
var1 = 5
var2 = 6

function globalvar(n)
    return getfenv()[“var”..n]
end

print(globalvar(1))

there’s a billion reasons not to do this and your script will become slower. go wild.

yea I think the table idea I had is a lot safer then using getfenv()

1 Like