Is it possible to combine two strings to get the name of a variable?

So, I’m attempting to combine two strings to find the name of a dictionary variable… But everything I try is just returning ‘nil’. Is this even possible to do? If so…how?

Any help would be much appreciated! :slight_smile:

Basic Code of what I’m trying to do.

local string1 = "My"
local string2 = "Dictionary"

local My_Dictionary = {
    one = "Heyyo",
    two = "byeee"

print((string1 .. "_" .. string2)["one"])

You won’t be able to do it this way. If you wanted to do something like this it would need to be structured a bit differently. Try:

local str1 = 'My';
local str2 = 'Dictionary';

local dictionaries = {
    My_Dictionary = {
        one = 'Heyyo',
        two = 'byeee',

print(dictionaries[str1.. '_' ..str2].one); -- Prints Heyyo
print(dictionaries[str1.. '_' ..str2]['one']); -- Also prints Heyyo

You’ll need to be careful with this approach though, since if str1.. '_' ..str2 is not in the dictionary of dictionaries you’ll get a nil lookup error.


If I wanted to check if bools were enabled or disabled, would I need to follow the same approach of putting them inside of a dictionary?

Can you give an example of what you’re asking?


local string1 = 'My'
local string2 = 'Bool'
local My_Bool = false

if (string1.. "_" .. string2) == false then
    (string1.. "_" .. string2) = true

super basic script but hopefully that explains it.

You won’t be able to do a string lookup on local variables like that. You’ll have to store them in a hash table first.

This would be one way to do it:

local str1 = 'My';
local str2 = 'Bool';
local values = {
    My_Bool = false,

if (values[str1.. '_' ..str2] == false) then
    values[str1.. '_' ..str2] = true;
1 Like

I haven’t tested this, but I think this would work. Although I’m not sure if it’s good practice to be using getfenv like this…

print(getfenv(0)[(string1 .. "_" .. string2)]["one"])
1 Like

I don’t think this will work. Doesn’t getfenv only return global variables within the given scope?

Maybe. I don’t really use it that much…

How could I insert a new variable into the table (after the table has been initialized)?

(I think with table.insert…but never used it)

local values = {
    My_Bool = false,

table.insert(values, "NewBool")

values.NewBool = true


values.NewBool = false

1 Like

You won’t want to use table.insert here as that is designed for an array implementation on a table. This works off of a Hashmap. To insert a new value simply do

local values = {
    My_Bool = false

values['NewBool'] = true; -- Or whatever you want it to equal here.
values.NewBool = true; -- This works too.

Then your lookup can be:

print(values['NewBool']); -- prints true
print(values.NewBool); -- prints true
1 Like

Awesome. Thanks again! You’ve been very helpful for me today!!