Lua中返回具有最大值的表格的对象名称

我试图返回具有最大值的对象的名称。 假设有以下信息:

maxTreeHeight = 0
maxTreeName = ""
maxLeaveLength = 0
maxLeaveName = ""

fruitTab =
 {
   oF = { name = "橙子", avgTreeHeight = 32, avgLeaveLength = 0.27 },
   aF = { name = "苹果", avgTreeHeight = 10, avgLeaveLength = 0.14 },
   bF = { name = "香蕉", avgTreeHeight = 16, avgLeaveLength = 8.9 },
   mF = { name = "芒果", avgTreeHeight = 115, avgLeaveLength = 0.98 }
 }

-- 在以下函数中
 for i,v in ipairs(fruitTab) do
   if v.avgTreeHeight > maxTreeHeight then
      maxTreeHeight = v.avgTreeHeight
      maxTreeName  = v.name
   end
   if v.avgLeaveLength > maxLeaveLength then
      maxLeaveLength = v.avgLeaveLength
      maxLeaveName = v.name
   end
 end

   print(maxLeaveName.." "..maxLeaveLength )
   print(maxTreeName.." "..maxTreeHeight)

这种设置是我尝试提取所需信息的方式,但是函数并不总是给我精确的值(根据我所看到的,具有最大值的名称并不总是正确的)

点赞
用户2505965
用户2505965

不确定您如何使用该代码获得任何结果,除非您的一些输入表是无键的。

ipairs 函数遍历表的 _索引_,仅用于类似于数组的表。相反,您应该使用 pairs 函数,它通过使用 next 遍历表中的每一个 _字段_。

仅仅进行这种更改即可从您的示例代码中获得结果。

以下是一些更新后的代码:

function get_max (tab)
    local maxTreeHeight = 0
    local maxTreeName = ""
    local maxLeaveLength = 0
    local maxLeaveName = ""

    for _, v in pairs(tab) do
       if v.avgTreeHeight > maxTreeHeight then
          maxTreeHeight = v.avgTreeHeight
          maxTreeName  = v.name
       end

       if v.avgLeaveLength > maxLeaveLength then
          maxLeaveLength = v.avgLeaveLength
          maxLeaveName = v.name
       end
    end

    print(maxLeaveName.." "..maxLeaveLength )
    print(maxTreeName.." "..maxTreeHeight)
end

local fruitTab = {
    oF = { name = "Orange", avgTreeHeight = 32, avgLeaveLength = 0.27 },
    aF = { name = "Apple", avgTreeHeight = 10, avgLeaveLength = 0.14 },
    bF = { name = "Banana", avgTreeHeight = 16, avgLeaveLength = 8.9 },
    mF = { name = "Mango", avgTreeHeight = 115, avgLeaveLength = 0.98 }
}

get_max(fruitTab)
2016-07-03 22:54:31