【问题标题】:How to get ONE of the lowest values from large table LUA?如何从大表 LUA 中获取最低值之一?
【发布时间】:2014-03-05 06:21:17
【问题描述】:
playerElement = { 
    { itemName="Ammo clip", value="30" },
    { itemName="Ammo clip", value="30" },
    { itemName="Ammo clip", value="30" },
}

如何检索表中的第一项(当所有项的值都相等时)以及如果不是具有最低值的项,那么我可以用 1 减去它?

【问题讨论】:

    标签: math lua lua-table


    【解决方案1】:

    根据您的表结构,您需要先扫描整个表才能做到这一点。

    local lowestIndex = 0;
    local lowestValue = false;
    for k, v in ipairs(playerElement) do
        if not lowestValue or v.value < lowestValue then
            lowestIndex = k;
            lowestValue = v;
        end
    end
    
    playerElement[lowestIndex].value = lowestValue - 1;
    

    附:我在路上打字,很抱歉有任何语法错误。

    【讨论】:

    • 我收到了建议的评论,据说是通过删除分号来纠正语法错误——它们不是语法错误,而只是可选的行尾。它们在 Lua 中是完全可以接受的(或者是我最后一次检查,大约是 Lua 5.2)。
    【解决方案2】:

    我开始学习 Lua,我使用 underscore-lua 库来解决您的问题。

    local _ = require 'underscore'
    
    -- here you define the playerElement table
    -- playerElement = {}
    
    -- create table of values
    local values = _.map(playerElement, function(t) return t.value end)
    
    -- get max and min values
    local max = _.max(values)
    local min = _.min(values)
    
     -- get first item when all the values are equal, if not the item with the lowest value
     if max == min then
       return playerElement[1]
     else
       return _.findWhere(playerElement, {value=tostring(min)})
     end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      • 1970-01-01
      • 2020-03-29
      相关资源
      最近更新 更多