Robert Holland
Robert Holland

Reputation: 1

How to automatically create variables in Lua?

Before I start, I'll say I am a beginner at Lua, so may not know all the correct terms, but I'll do my best to explain what I'm after.

I have a table (data) that contains other tables. When data is first created, it can have any number of tables inside it (I expect this to be between 1 and 50).

I want to assign each table to it's own variable.

If I know how many tables there are then this is easy using table1 = data[1]; table2 = data[2] and so on.

I've done a count on the data so that I know the number of entries there are so what I want to do is automatically create the variables, give them a name and assign the corresponding table to it.

So lets say data contains 10 tables. I then want variables created called table1, table2, table3 and so on. table1 should be data[1], table2 should be data[2] and so on.

I'm certain I should create a loop and every time round, have a count=count+1 to create the number attached to the variable.

The problem I have is that I have no idea how to create a variable called 'table'+count (table1).

How do I join the 2 together?

Upvotes: 0

Views: 1088

Answers (2)

Doug Currie
Doug Currie

Reputation: 41220

The way to create a global variable with a constructed name is to update the global table _G

_G['table'..count] = data[count]

E.g.,

Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> count = 3
> _G['table'..count] = 17
> = table3
17
> 

Upvotes: 7

colinbrownec
colinbrownec

Reputation: 81

You can't, very few programming languages support this and those that do do so through reflection.

The easiest way is to keep your table of tables! All of your tables are stored there already and you can easily refer to a specific table by using data[x] When you do it this was you can refer to your tables using only their index.

Upvotes: -1

Related Questions