如何在表

时间:2016-02-06 05:19:20

标签: lua iterator lua-table

bestSword = {
  {name = 'www' , lvl = 35, atk = 38, npcPrice = 15000 , buyPrice = 0},
  {name = 'bbb' , lvl = 40, atk = 40, npcPrice = 20000 , buyPrice = 0},
  {name = 'eee' , lvl = 50, atk = 42, npcPrice = 25000 , buyPrice = 0},
  {name = 'sss' , lvl = 55, atk = 43, npcPrice = 30000 , buyPrice = 0},
  {name = 'aaa' , lvl = 60, atk = 44, npcPrice = 30000 , buyPrice = 0},
  {name = 'qwe' , lvl = 70, atk = 46, npcPrice = 35000 , buyPrice = 0},
  {name = 'asd' , lvl = 82, atk = 48, npcPrice = 60000 , buyPrice = 0}
}

我有这个表,如何从最后一个索引迭代到第一个?它应该打破取决于lvl。我只想用最好的武器展示这张桌子。例如,如果玩家有等级53,那么我想只显示他lvl或更低的武器。我需要从最好的(顶部)显示它为什么我想从最后一个索引迭代。有人可以帮忙吗?

编辑: 感谢帮助。还有一个问题,我以后需要这个更改的表。它显示一切正常但我需要稍后从这个(更改)列表中购买所有文字。所以我必须以某种方式替换这两张桌子。有没有简单的方法呢?我试图从这个表中删除元素,但它仍然不起作用。

或者可以在Lua制作一些地图?它必须是动态大小,所以我不能使用表我猜。键值的东西

2 个答案:

答案 0 :(得分:4)

数字for循环,倒计时,是最好的选择:

local t = {2,4,6,8}

for i = #t, 1, -1 do
    print(t[i])
end

答案 1 :(得分:1)

假设表格不一定按等级排序(与示例不同),我们需要做两件事:

  • 查找哪些剑在等级范围内
  • 按降序排序

现在临时表中的第一个是"最好的"剑。

像这样:

bestSword = {
  {name = 'www' , lvl = 35, atk = 38, npcPrice = 15000 , buyPrice = 0},
  {name = 'bbb' , lvl = 40, atk = 40, npcPrice = 20000 , buyPrice = 0},
  {name = 'eee' , lvl = 50, atk = 42, npcPrice = 25000 , buyPrice = 0},
  {name = 'sss' , lvl = 55, atk = 43, npcPrice = 30000 , buyPrice = 0},
  {name = 'aaa' , lvl = 60, atk = 44, npcPrice = 30000 , buyPrice = 0},
  {name = 'qwe' , lvl = 70, atk = 46, npcPrice = 35000 , buyPrice = 0},
  {name = 'asd' , lvl = 82, atk = 48, npcPrice = 60000 , buyPrice = 0}
}

myLevel = 53  -- wanted level

-- temporary table
possible = { }

-- extract ones which are in range
for k, v in ipairs (bestSword) do
  if v.lvl <= myLevel then
    table.insert (possible, v)
  end -- if
end -- for

if #possible == 0 then
  print "No matching swords"
else
  table.sort (possible, function (a, b) return a.atk > b.atk end )
  bestSword = possible [1]
  print ("Best sword is", bestSword.name, "lvl =", bestSword.lvl,
         "atk = ", bestSword.atk)
end -- if
  

或者可以在Lua制作一些地图?它必须是动态大小,所以我不能使用表我猜。键值的东西

Lua 中的表是地图。每个表都有键/值对。你在那里使用的只是数字键表。

所有表都是动态大小的。