lua Adding key value pair in nested table

Viewed 26

Im new to lua and have a problem which i believe has an elegant solution, but i just cant make it work. I've read similar questions and answers here on stack overflow and elsewhere for hours as well as testing in online lua compiler but no real progress.

Q:

i start out with an empty table:

local vertices = {}

Now, with a for loop or similar i want to populate this table so the end result has this form:

local vertices = {
{x=-6.0, y=0.0},
{x=0.0, y=1},
}

Where the values in the entries {x=-6.0, y=0.0} are arbitrary, and the number of these {x=0.0, y=1} (coordinates) are also arbitrary.

These values are to be fetched from another table and som calculated in the for loop, but that is the next step. For now i just need help populate my empty table with x,y values in a loop.

Thanks to you all.

1 Answers

You can add elements to a Lua table through

the table constructor local t = { v1, v2, v3 }

assignment t[k1] = v1 t[k2] = v2

table.insert(t, 1) (for consecutive integer indices starting at 1)

rawset(t, 1, 1) if you want to avoid invoking metamethods

table.move to copy elements fro one to another table

...

For your case you can simply use assignment in a for loop.

local vertices = {}
for i = 1, 100 do
  vertices[i] = NewVertex();
end

To add 100 vertices to the table.

Related