Reputation: 673
I am trying to run this code:
function calcs.grps(Number,ion_color)
grp .. ion_color .. Y[Number] = (ion_py_mm)
grp .. ion_color .. Z[Number] = (ion_pz_mm)
end
in a Lua script, the arrays already exist (eg grp2Y,grp5Z etc) and I want to use this function to populate them based upon the two variables fed in. I keep getting the error ' '=' expected near '..' '. What am I doing wrong?
To flesh it out a bit:
I am 'flying' 120 ions in my simulation. This is actually 12 groups of 10 ions. The individual groups of 10 are distinguished by ion_color, which is an integer value from 1 to 12. The variable 'Number' just cycles through 1 to 10 each time before moving on to the next color. Once I have populated these arrays I want to get the standard deviation for each group.
Thank you!
Upvotes: 1
Views: 62
Reputation: 3113
The technical answer to your question is to simply index _G, _G is a table which holds all global variables:
function calcs.grps(Number,ion_color)
_G['grp' .. ion_color .. Y'][Number] = (ion_py_mm)
_G['grp' .. ion_color .. 'Z'][Number] = (ion_pz_mm)
end
But I think the better question, is why aren't you organizing it like this...
local ions = {
Red = {
{
Y = 0, --Y property
Z = 0 --Z property
},
--Continue your red ions
},
NewColor = {
Y = 0, --Y property
Z = 0 --Z property
},
--Continue this color's ions
},
--You get the idea
}
function calcs.grps(color, number)
ions[color][number].Y = (ion_py_mm)
ions[color][number].Z = (ion_pz_mm)
end
Then you would pass a color, and a number indicating which ion of this color
It looks a lot cleaner, IMO.
Upvotes: 1
Reputation: 22431
You can't "construct" name of variable, but you can construct an index. Use two levels of nested tables.
function calcs.grps(Number,ion_color)
ion['grp' .. ion_color .. 'Y'][Number] = (ion_py_mm)
ion['grp' .. ion_color .. 'Z'][Number] = (ion_pz_mm)
end
Well, actually you can, since all global variables are just entries in _G
table, but don't do that since it is bad - it is unreadable, makes stuff spill to other functions you didn't intend to, etc.
Upvotes: 3