Search code examples
lua

How would i make a key value pair into a variable and value


If I have a given dictionary how would I make the key name into the name of a variable and assign the keys value to that variable. For example if I have the dictionary num = {num1 = 1, num2 = 2, num3 = 3}, I want to be able to have the variable num1 = 1 , num2 = 2 and num3 = 3. This is an example dictionary but I need this for a particular function where the number of items in the dictionary is unknown and the elements of the dictionary are also unknown. What I've tried so far is:

local num = {num1 = 1, num2 = 2, num3 = 3}


local keys = {}

local values = {}


for name,value in pairs(num) do
    table.insert(keys,name)
    table.insert(values,value)
end

for i,v in pairs(keys) do 
    print(v,values[i])
end

The last for loop is pretty much there just to show how I wanted to access each key, value pair but I don't know how I would go about making them into the form variable = value were the variable is available globally.


Solution

  • You cannot convert table items into variables. Your best bet is to either manually create the variables or read off the table

    print(nums.num1) -- returns 1