【发布时间】:2014-03-05 06:21:17
【问题描述】:
playerElement = {
{ itemName="Ammo clip", value="30" },
{ itemName="Ammo clip", value="30" },
{ itemName="Ammo clip", value="30" },
}
如何检索表中的第一项(当所有项的值都相等时)以及如果不是具有最低值的项,那么我可以用 1 减去它?
【问题讨论】:
playerElement = {
{ itemName="Ammo clip", value="30" },
{ itemName="Ammo clip", value="30" },
{ itemName="Ammo clip", value="30" },
}
如何检索表中的第一项(当所有项的值都相等时)以及如果不是具有最低值的项,那么我可以用 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,我使用 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
【讨论】: