Gullie667
Gullie667

Reputation: 91

How to access a table using a string in Lua

I am trying to remove mainMenuButtonGroup1 through mainMenuButtonGroup6.

To do this I think I need to do the following: [mainMenuButtonGroup..n] How would I do that?

local mainMenuButtonGroup1 = { 1,2 }
local mainMenuButtonGroup2 = { 3,4 }
local mainMenuButtonGroup3 = { 5,6 }
local mainMenuButtonGroup4 = { 7,8 }
local mainMenuButtonGroup5 = { 9,10 }
local mainMenuButtonGroup6 = { 11,12 }

for n = 1, 6 do
      [mainMenuButtonGroup..n] = nil
end

Upvotes: 2

Views: 1186

Answers (2)

John Zwinck
John Zwinck

Reputation: 249093

Assuming the variables are global, they will be in the _G table:

for n = 1, 6 do
   for i = _G['mainMenuButtonGroup'..n].numChildren, 1, -1 do
      _G['mainMenuButtonGroup'..n][i]:removeSelf()
      _G['mainMenuButtonGroup'..n][i] = nil
   end
end

If they are local, you can use debug.getlocal, but you will have to loop over all the locals until you find the names you want. Not ideal, but possible.

Upvotes: 1

Ryan Stein
Ryan Stein

Reputation: 8000

Based on your comments, I assume this is something like what you want to do, where t is the table that you mentioned.

for i = 1, 6 do
    local k = 'mainMenuButtonGroup' .. i
    t[k]:removeSelf()
    t[k] = nil
end

String concatenation is performed by the .. double period operator, and table indexing via . or []. In this case, you're indexing via [] because you're using a variable and not a constant name.


Edit: Put your similar local variables into a table instead. It makes it far, far easier to iterate as a group. In fact, the only way I know of to iterate locals is through the debug library.

local mainMenuButtonGroup = { {1,2}, {3,4}, {5,6}, {7,8}, {9,10} }
table.insert(mainMenuButtonGroup, {11,12})

for i = 1, 6 do
    mainMenuButtonGroup[i] = nil
end

Note, however, that setting a numeric index in a table to nil does not rearrange the table's numerically indexed values. I.e., you'll leave the table with holes. See table.remove.

Upvotes: 2

Related Questions