Lua及三种要求“if”语句。

我在摆弄一些我在一些 forum 上找到的代码,但我只学过 Java,所以我有点不在自己的领域。这是我正在使用的代码段:

/run
function FnH()
  for i=0,4 do
    for j=1,GetContainerNumSlots(i) do
      local t={GetItemInfo(GetContainerItemLink(i,j) or 0)}
      if t[7]=="Herb" and select(2,GetContainerItemInfo(i,j))>=5 then
        return i.." "..j, t[1]
      end
    end
  end
end

这里使用了 WoW 的插件 API。根据我所知,这是一个搜索和制作列表函数,其中列出让 t[7]=Herb 且数量大于 5 的物品。如果 Lua 以类似的方式处理数组,t[0] 应该是物品名称。我想排除名称为“blahblah”的物品,但我不理解 Lua 的布尔运算符。

在 Java 中,它可能是这样的

if(itemX.getItemType()=="Herb" && itemX.getAmount()>5 && itemX.getName()!="blahblah")
do stuff
else skip to next item

我看到 Lua 使用“and”和“or”,但我怎么说“and not this”呢?

点赞
用户1442917
用户1442917

如果 Lua 的数组类似的话,t[0] 应该是物品名称。

请注意 Lua 索引表格是从索引1开始的,而不是像其他语言一样从0开始,所以如果您有一个表格 local t = {"John", "Laura", "Herb"},那么 t[1] == "John"t[3] == "Herb"

就像其他人所说,等价的 Lua 操作是 andornot,不等式写作 ~=,所以您拥有的代码可以写成:

if itemX.getItemType() == "Herb"
and itemX.getAmount() > 5
and itemX.getName() ~= "blahblah" then
  -- 做一些操作
else
  -- 跳到下一个物品
end

您也可以将最后一个条件改为 and not (itemX.getName()=="blahblah"),因为它们是等价的。

此外,我不确定 WoW API,但这些 itemX 调用应该是 itemX:getItemType()itemX:getAmount(),等等(请注意使用冒号:符号而不是点号.符号);查看《Lua程序设计》中的OO编程部分。

2014-12-05 17:16:40
用户4333718
用户4333718

我将直接将你的 Java 代码翻译成 Lua,你可以看看它是否对你有意义

if itemX.getItemType() == "Herb" and itemX.getItemAmount() > 5 and itemX.getItemName ~= "blahblah" then 
    --在这里执行操作
else
    --跳到下一个项
end
2014-12-07 15:47:26