在循环中进行交互以获取数组中的字段值的最佳方法

时间:2018-03-29 19:08:04

标签: lua

我有一个数组,我正在翻阅以处理一些文本行。这段代码有效,但我知道必须有更好的方法来实现它。

 local text_matches = {
                  {"^range:","range"},
                  {"^saving throw:","save"},
                  {"^casting time:","castingtime"},
                  {"^components:","components"},
                  {"^area of effect:","aoe"},
                  {"^duration:","duration"},
                  {"^school:","school"},
                  {"^sphere:","sphere"},
                  {"^type:","type"},

                  {"^arcane ","school","(.*)$"},
                  {"^phantasmal ","school","(.*)$"},
                  {"^druidic ","sphere","(.*)$"},
                  {"^clerical ","sphere","(.*)$"},

                  };

然后我在for循环中使用text_matches

  for _, sFind in ipairs(text_matches) do
    local sMatch = sFind[1];
    local sValue = sFind[2];
    local sFilter = sFind[3];
    if (string.match(sLine:lower(),sMatch)) then
      bProcessed = true;
      setTextValue(nodeSpell,sLine,sMatch,sValue,sFilter);
    end
  end

我不必像我一样为sMatch / sValue / sFilter赋值。我对Lua的某些方面还不熟悉,但我怀疑必须有一种方法可以使用for循环并为数组中的每个条目获取所有3个值?

类似于for sMatch, sValue, sFilter (text_matches) do

1 个答案:

答案 0 :(得分:1)

确实有办法。 ipairs是一个迭代器。没有人阻止你写自己的。

让我们来看看ipairs的工作原理:

function iter (a, i)
  i = i + 1
  local v = a[i]
  if v then
    return i, v
  end
 end

 function ipairs (a)
   return iter, a, 0
 end

有关详细信息,请参阅Programming in Lua: 7.3 Stateless Iterators

  

当Lua在ipairs(a)循环中调用for时,它会获得三个值:   iter用作迭代器,a用作不变状态,和   zero作为控制变量的初始值。然后,Lua打来电话   iter(a, 0),结果为1, a[1](除非已a[1]   nil)。在第二次迭代中,它调用iter(a, 1),结果   在2, a[2]中,依此类推,直到第一个nil元素。

现在我们将返回a[i]a[i][1]a[i][2]而不是a[i][3]

function myFancyThree(a)

    return function(a, i)
             i = i + 1
             local v = a[i]
             if v then
               return i, v[1], v[2], v[3]
             end
           end, a, 0
end

然后我们可以做类似

的事情
for i, a,b,c in myFancyThree(text_matches) do
  print(a,b,c)
end

我没有过多考虑它。我确信有些事情你可以做得更好,但它应该足以让你开始。

只需阅读有关通用for循环,迭代器和无状态迭代器的任何内容,您可以在Lua编程和Lua参考手册中找到它。

我让你找到比myFancyThree更好的名字:)