lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


It was thus said that the Great iain morland once stated:
> Hi all,
> 
> I've created a table that contains a series of sequentially numbered
> variables. I'd like to retrieve those variable names from the table, in
> order to set an attribute that exists for those variables in the
> implementation of Lua that I'm using (5.1 with custom extensions in MOTU
> MachFive), but I'm having problems because Lua seems to interpret the names
> as strings, rather than as variables. I'm sure the fault is my lack of
> understanding, rather than a problem in Lua. :-s
> 
> So for example, here's my table of variables:
> ---
> MyTable={}	
> for i = 0,9 do
> 	MyTable[i]="Variable"..i
> end
> ---

  You could try doing this:

	MyTable = {}
	for i = 0 , 9 do
	  local name = "Variable" .. i
	  MyTable[name] = {}
	end

  Then you would be able to do

	MyTable.Variable0.attribute = value
	MyTable.Variable1.attribute = value

> Later on, to set the attribute, I could do this for each variable (0-9):
> Variable0.attribute=value
> Variable1.attribute=value
> ..and so on (both attribute and value are the same in each case).
> 
> Instead of writing a line for each variable, I'd like to use the contents of
> the table, like so:
> ---
> for i=0,9 do
> 	print(MyTable[i])	--this works fine
> 	MyTable[i].attribute=value	--this doesn't work ("attempt to
> index a string value"). 
> end
> ---
> 
> So how could I get the string that's returned by MyTable[i] to be "seen" by
> Lua as a variable name?

  Um ... _G[MyTable[i]].attribute?  So what exactly are you trying to do?

  -spc