Shejo284
Shejo284

Reputation: 4771

Dynamically building subtables in a table

I'm trying to figure out how to dynamically build a series of sub-tables inside a lua table. For example

function BuildsubTable()
   local oTable = {}
   local name  = {"P1","P2"}
  for i = 1, 2 do
    oTable[i] = {name = name[i], "x" = i + 2, "y" = i + 1}
  end
  return oTable
end

expected output:

 oTable = {
  {name = "P1", "x"=3, "y"=2},
  {name = "P2", "x"=4, "y"=3}
 }

Which obviously doesn't work, but you get the idea of what I'm trying to do. This is a rather simple task but in LUA 5.3 this is proving to be difficult. I cannot find a good example of building a table in this manner. Any solutions or other ideas would be appreciated. In Python I would use a class or a simple dictionary.

Upvotes: 2

Views: 1025

Answers (3)

wsha
wsha

Reputation: 964

DarkWiiPlayers & lhf's answers are the proper way. But here is how you can fix your current code if you intend to use a string as a key

function BuildsubTable()
   local oTable = {}
   local name  = {"P1","P2"}
  for i = 1, 2 do
    oTable[i] = {name = name[i], ["x"] = i + 2, ["y"] = i + 1}
  end
  return oTable
end

Output

{
    [1] = { ['name'] = 'P1', ['x'] = 3, ['y'] = 2},
    [2] = { ['name'] = 'P2', ['x'] = 4, ['y'] = 3}
}

Upvotes: 3

DarkWiiPlayer
DarkWiiPlayer

Reputation: 7064

Your problem is that you quote the string indices. The generic syntax for declaring a table key inside the table constructor is [<key>] = <value>, for example, [20] = 20 or ["x"] = i + 2.

A shorthand for ["<key>"] = <value>, that is, for string indices that are valid variable names, you can write <key> = <value>, for example x = i + 2.

In your code you use a mix of both and write { ..., "x" = i + 2, ... }. A quick google search shows me that in Python, which you mention, you quote string keys in dictionaries, so you probably mixed that up with Lua?

EDIT: I noticed this a bit late, but you can also use ipairs to iterate the first table and table.insert to insert values:

function BuildsubTable()
    local oTable = {}
    local name  = {"P1","P2"}
    for i,name in ipairs(name) do
        table.insert(oTable, {name = name, "x" = i + 2, "y" = i + 1})
    end
    return oTable
end

Upvotes: 4

lhf
lhf

Reputation: 72412

Use

oTable[i] = {name = name[i], x = i + 2, y = i + 1}

Upvotes: 4

Related Questions