Jeron
Jeron

Reputation: 36

Lua: how use all tables in table

positions = {
--table 1
[1] = {pos = {fromPosition = {x=1809, y=317, z=8},toPosition = {x=1818, y=331, z=8}}, m = {"100 monster"}},
--table 2
[2] = {pos = {fromPosition = {x=1809, y=317, z=8},toPosition = {x=1818, y=331, z=8}}, m = {"100 monster"}},
-- table3
[3] = {pos = {fromPosition = {x=1809, y=317, z=8},toPosition = {x=1818, y=331, z=8}}, m = {"100 monster"}}
}

    tb = positions[?]--what need place here?

for _,x in pairs(tb.m) do --function
    for s = 1, tonumber(x:match("%d+")) do
    pos = {x = math.random(tb.pos.fromPosition.x, tb.pos.toPosition.x), y = math.random(tb.pos.fromPosition.y, tb1.pos.toPosition.y), z = tb.pos.fromPosition.z}
    doCreateMonster(x:match("%s(.+)"), pos)
    end
    end

Here the problem, i use tb = positions[1], and it only for one table in "positions" table. But how apply this function for all tables in this table?

Upvotes: 0

Views: 135

Answers (3)

Mike Corcoran
Mike Corcoran

Reputation: 14564

use the pairs() built-in. there isn't any reason to do a numeric for loop here.

for index, position in pairs(positions) do
    tb = positions[index]
    -- tb is now exactly the same value as variable 'position'
end

Upvotes: 0

prapin
prapin

Reputation: 6898

You need to iterate over positions with a numerical for.

Note that, unlike Antoine Lassauzay's answer, the loop starts at 1 and not 0, and uses the # operator instead of table.getn (deprecated function in Lua 5.1, removed in Lua 5.2).

for i=1,#positions do
  tb = positions[i]
  ...
end

Upvotes: 2

Antoine Lassauzay
Antoine Lassauzay

Reputation: 1607

I don't know Lua very well but you could loop over the table:

for i = 0, table.getn(positions), 1 do
     tb = positions[i]
     ...
end

Sources : http://lua.gts-stolberg.de/en/schleifen.php and http://www.lua.org/pil/19.1.html

Upvotes: 2

Related Questions