Search code examples
for-loopluatreelua-table

Searching through tables (String name) with for loop (in Lua)


I got following problem (in Lua):

I have 20 tables named tree01, tree02 , ... , tree20.
Now I want to search the content of these tables but I can't find a solution how to refer to a tree with for.

for i=tree01,tree20 do
 --blablabla

Obviously I can't count it this way. Anybody got an idea?


Solution

  • If tree[1], ..., tree[20] are global variables then you can do this:

    for i=1,20 do
      local t=_G[string.format("tree%02d",i)]
      -- blablabla
    end
    

    But it'd be much better if you had one table containing 20 tables: tree[1], ..., tree[20].