nikitaforeveryday
nikitaforeveryday

Reputation: 3

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?

Upvotes: 0

Views: 116

Answers (1)

luther
luther

Reputation: 5564

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'])

Upvotes: 2

Related Questions