0
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?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Jeron
  • 36
  • 4

3 Answers3

2

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

Antoine Lassauzay
  • 1,557
  • 11
  • 12
  • Tested. it returns: attempt to index local 'tb' (a nil value) I will test this code with diff variations, becouse i dont have any idea why it return nil to me. – Jeron Dec 08 '12 at 13:14
  • Solved: `for i,x in ipairs(positions) do tb=positions[i] end` – Jeron Dec 08 '12 at 13:47
2

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
prapin
  • 6,395
  • 5
  • 26
  • 44
0

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
Mike Corcoran
  • 14,072
  • 4
  • 37
  • 49