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!
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.
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;
end
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