【问题标题】:Lua: how use all tables in tableLua:如何使用表中的所有表
【发布时间】:2013-03-06 21:18:34
【问题描述】:
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

这里的问题是,我使用 tb = position[1],它只用于“位置”表中的一个表。但是如何将这个函数应用于这个表中的所有表呢?

【问题讨论】:

    标签: syntax lua lua-table


    【解决方案1】:

    我不太了解 Lua,但您可以遍历表格:

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

    来源: http://lua.gts-stolberg.de/en/schleifen.phphttp://www.lua.org/pil/19.1.html

    【讨论】:

    • 经过测试。它返回:尝试索引本地 'tb'(一个 nil 值)
    • 已解决:for i,x in ipairs(positions) do tb=positions[i] end
    【解决方案2】:

    您需要使用数字 for 迭代 positions

    请注意,与 Antoine Lassauzay 的回答不同,循环从 1 而不是 0 开始,并使用 # 运算符而不是 table.getn(在Lua 5.1,在 Lua 5.2 中删除)。

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

    【讨论】:

      【解决方案3】:

      使用内置的 pairs()。没有任何理由在这里进行数字 for 循环。

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

      【讨论】:

        猜你喜欢
        • 2014-08-19
        • 1970-01-01
        • 2021-04-05
        • 2011-06-20
        • 2012-09-17
        • 1970-01-01
        • 1970-01-01
        • 2021-02-06
        • 1970-01-01
        相关资源
        最近更新 更多