lua-users home
lua-l archive

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


2013/3/29 iain morland <iain@iainmorland.net>:
> 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
> ---
> 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?

Basically summarizing the reponses so far:

S={"s1","s2","s3","s4"}
for k,v in ipairs(S) do _G[v]={} end
s1.name = "Jack"
s3.age = 42
for k,v in ipairs(S) do print(k,next(_G[v])) end

1	name	Jack
2	nil
3	age	42
4	nil