Lisa
Lisa

Reputation: 21

A way to use dynamic variable names?

In Lua, is there a way to use dynamic variable names such as having the name of a variable contained in a variable?

Say I want a variable to be named "myvar2", but don't want to hard code it as in:

myvar2 = 55

But instead have another variable such as "varname" contain the name "myvar2"?

Example:

varname = "myvar2"

*varname = 25

print(myvar2)  --->  25

Upvotes: 2

Views: 989

Answers (1)

ryanpattison
ryanpattison

Reputation: 6251

One method is to look-up variables by name in the global environment, the table _G:

 varname = "myvar2"
 _G[varname] = 25
 print(myvar2) ---> 25

Note that this will not find local variables. Useful reading: PIL 14.1 – Accessing Global Variables with Dynamic Names

Upvotes: 5

Related Questions