Search code examples
variableslua

Get the content of a variable with the same name in Lua


I have two variables, like Stefan and StefanDouble. I have a String variable that contains for "Stefan". How can I get the contents of a variable with the same name and a variable with Double at the end? Is there any reason to do this?


Solution

  • Any time you find yourself storing a variable name in another variable, you should instead store those "variables" inside a table. Real variables are for storing information that's inherent to your algorithm, while tables are for storing unknown amounts of data.

    local myVars = {
      Stefan = 1,
      StefanDouble = 2,
    }
    
    local myString = 'Stefan'
    print(myVars[myString])
    print(myVars[myString .. 'Double'])