0

I'm trying to load data values of data categories of a database into tables for further processing. Each data category is supposed to get its own table. Unfortunately, the number of data categories isn't consistent and varies from DB to DB, so I thought about creating tables automatically according to the amount of present data categories:

--categories is a table containing the names of all data categories
for a = 1, #categories, 1 do 
temptable..a = {}; 
end

This of course doesn't work, since Lua tries to assign the table to the variable instead of its value. Variable concatenation is also not possible this way. Is there a way to actually get Lua to create tables automatically?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Zerobinary99
  • 542
  • 2
  • 8
  • 17

1 Answers1

5

Remember in Lua tables can contain tables so why not simply do it that way

For example

cat = {'cat1','cat2','cat3'}

temptable = {}
for i,v in pairs(cat) do
temptable[v] = {1+ i,2 + i,3 + i}
end

Would give you a table containing temptable

[cat2] => table
    (
       [1] => 3
       [2] => 4
       [3] => 5
    )
[cat1] => table
    (
       [1] => 2
       [2] => 3
       [3] => 4
    )
[cat3] => table
    (
       [1] => 4
       [2] => 5
       [3] => 6
    )

Which could be accessed using

for i,v in pairs(temptable.cat1) do
print(i,v)
end
Jane T
  • 2,081
  • 2
  • 17
  • 23
  • 2
    And remember that the global environment is `_G`, so you can do `_G[v]` rather than `temptable[v]`, and they will show up as global variables rather than members of `temptable`. – Michael Anderson May 31 '12 at 09:10