【问题标题】:Lua - Match a string with item in array?Lua - 将字符串与数组中的项目匹配?
【发布时间】:2014-12-22 05:19:40
【问题描述】:

我是 Lua 新手,我想尝试显示数组中的项目,但它就像数组中的数组。

这是我的清单:

local itemlist = {
    { name="blue car", price=5000 },
    { name="red car", price=10000 },
    { name="green car", price=2000 }
}

因此,如果我输入文本“红色汽车”,我希望它输出如下内容:

The red car costs 10000 dollars.

如何在 lua 中做到这一点? 到目前为止,我只找到了一些字符串匹配示例,我可以在其中查看数组是否包含项目,但我想要的是输出那个和价格。我如何获得价格?我什至不知道从哪里开始。

【问题讨论】:

    标签: arrays string lua pattern-matching


    【解决方案1】:

    您应该阅读手册中的表格和带有序列的表格。然后您可以决定是使用pairs 还是ipairs 来遍历表。

    如果名称是唯一的,另一种方法是改变结构:

    local itemlist = {
        ["blue car"] = { price=5000 },
        ["red car"] = { price=10000 },
        ["green car"] = { price=2000 }
    }
    
    -- or even 
    
    local prices = {
        ["blue car"] = 5000,
        ["red car"] = 10000,
        ["green car"] = 2000
    }
    
    print(itemlist["red car"].price);
    print(prices["red car"]);
    

    【讨论】:

      【解决方案2】:

      在您的简单示例中,您不需要模式匹配。

      local str = "red car"
      for _, v in ipairs(itemlist) do
          if v.name == str then
              print("The " .. v.name .. " costs " .. tostring(v.price) .. " dollars.")
          end
      end
      

      【讨论】:

      • 它在列表中的第一项上效果很好,但第二项(红色汽车和绿色汽车)不会被打印出来。我输入了“蓝色汽车”,它完美地显示出来。 Ohhhhhhhhh nvm 现在可以使用了!谢谢!!!!
      • 顺便说一句,我怎样才能让“str”检查项目是否在列表中。而不是设置本地 str = red car”,就像我输入任何它会识别的项目名称一样。如果项目不在列表中,比如紫色汽车,它会说“我没有那辆车库存。”
      • @aliazik 使用像local found_car = false 这样的布尔标志,如果名称匹配,则将其设置为true 并跳出循环。循环完成后检查它的值。
      • 问题是,我这样做是为了一个小游戏。我输入的文本存储在一个名为 m.content 的变量中。所以我需要做的是,如果玩家输入“red car”,它将设置local str = "red car"。但我不想添加像 if (m.content == 'red car') then local str = "red car" elseif (m.content == 'blue car') then local str = "blue car" end 这样的长 if 语句。例如,如果我的列表包含 1000 个项目,那将花费大量时间
      • 没关系,我现在解决了! elseif (table.find(itemlist, m.content:lower(), 'name')) then
      猜你喜欢
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多