Dynamically created variables in for loop

469 views Asked by At

Is it possible to use a for loop to dynamically name variables? Something such as:

t = {} 

For i in ipairs(tablename) do
   t.i = something
End

My actual problem consists of dynamically creating protofields for a wireshark dissector, but if the above is not possible, I doubt the protofield problem will be possible

2

There are 2 answers

0
Colonel Thirty Two On BEST ANSWER

Just do t[i]. This will index the table (t) with a value i.

local t = {}

for i, _ in ipairs(othertbl) do
    t[i] = something
end

(Note that in Lua, foo.bar is short for foo["bar"]. Also note that the string "123" is different from the number 123)

2
odie2 On

I don't exactly understand your problem, but try following:

t = {}

for i in ipairs(tablename) do
    _G["t"][i] = tablename[i];
end

Or if you mean (I think that you mean) to create variable name containing number:

 local tablename = {"a", "b"}

 for i in ipairs(tablename) do
      _G["t"..i] = tablename[i];
 end

So you have "t1", "t2" variable.

_G[name] is used global variables (at least in Runes of Magic).

If _G[name] returning error, try setglobal(name) instead.