'Generate variable name with string and value in Lua

Is there a function in Lua to generate a variable name with a string and a value?

For example, I have the first (string) part "vari" and the second (value) part, which can vary. So I want to generate "vari1", "vari2", "vari3" and so on. Something like this: "vari"..value = 42 should then be vari1 = 42.

Thanks



Solution 1:[1]

Yes, but it most likely is a bad idea (and this very much seems to be an XY-problem to me). If you need an enumerated "list" of variables, just use a table:

local var = { 42, 100, 30 }
var[4] = 33 -- add a fourth variable
print(var[1]) -- prints 42

if you really need to set a bunch of variables though (perhaps to adhere to some odd API?), I'd recommend using ("..."):format(...) to ensure that your variables will be formatted as var<int> rather than var1.0, var1e3 or the like.

Th environment in Lua - both the global environment _G and the environment of your script _ENV (in Lua 5.2), which usually is the global environment, are just tables in the end, so you can write to them and read from them the same way you'd write to and read from tables:

for value = 1, 3 do
    _ENV[("vari%d"):format(value)] = value^2
end
print(var3) -- prints 3*3 = 9
-- verbose ways of accessing var3:
print(_ENV.var3) -- still 9
print(_ENV["var"]) -- 9 as well

Note that this is most likely just pollution of your script environment (likely global pollution) which is considered a bad practice (and often bad for performance). Please outline your actual problem and consider using the list approach.

Solution 2:[2]

Yes. Call:

rawset(table, key, value)

Example:

rawset(_G, 'foo', 'bar')
print(foo)
-- Output: bar
-- Lets loop it and rawget() it too
-- rawset() returns table _G here to rawget()
-- rawset() is executed before rawget() in this case
for i = 1, 10 do
 print(rawget(rawset(_G, 'var' .. i, i), 'var' .. i))
end
-- Output: 10 lines - First the number 1 and last the number 10

See: https://lua.org/manual/5.1/manual.html#pdf-rawset

Putting all together and create an own function...

function create_vars(var, start, stop)
for i = start, stop do
 print(var .. i, '=>', rawget(rawset(_G, var .. i, i), var .. i))
end
end

And use it...

> create_vars('var', 42, 42)
var42   =>  42
> print(var42)
42

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LMD
Solution 2