简体   繁体   English

如何在Lua中自动创建变量?

[英]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. 在开始之前,我会说我是Lua的初学者,所以可能不知道所有正确的用语,但我会尽力解释我要做什么。

I have a table ( data ) that contains other tables. 我有一个包含其他表的表( data )。 When data is first created, it can have any number of tables inside it (I expect this to be between 1 and 50). 首次创建data ,它内部可以具有任意数量的表(我希望它在1到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] 如果我知道有多少张表,那么使用table1 = data[1]; table2 = data[2]这很容易table1 = data[1]; table2 = data[2] table1 = data[1]; table2 = data[2] and so on. table1 = data[1]; table2 = data[2] ,依此类推。

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. 我已经对data进行了计数,因此我知道条目的数量,所以我要做的是自动创建变量,给它们命名并为其分配相应的表。

So lets say data contains 10 tables. 因此,可以说data包含10个表。 I then want variables created called table1 , table2 , table3 and so on. 然后,我想要创建名为table1table2table3等的变量。 table1 should be data[1] , table2 should be data[2] and so on. table1应该是data[1]table2应该是data[2] ,依此类推。

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. 我确定我应该创建一个循环,并且每次循环都有一个count=count+1来创建附加到变量的数字。

The problem I have is that I have no idea how to create a variable called 'table'+count ( table1 ). 我的问题是我不知道如何创建一个名为'table'+counttable1 )的变量。

How do I join the 2 together? 如何将2一起加入?

The way to create a global variable with a constructed name is to update the global table _G 创建具有构造名称的全局变量的方法是更新全局表_G

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

Eg, 例如,

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

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. 您所有的表都已经存储在那里,您可以通过使用data [x]轻松地引用特定的表。这样做时,您可以仅使用它们的索引来引用表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM