Question

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?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top