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
CodePudding user response:
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.
CodePudding user response:
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