如何获取最高值的键

function high(scorel)
    local highest = 0
    for name, score in pairs(scorel) do
        if score > highest then
           highest = score
        end
    end
    print(name)
end

打印最高分数者的键,键包含他或她的名字。

点赞
用户6632736
用户6632736

只需记住名称即可:

function high(scorel)
    local leader, highest = nil, 0
    for name, score in pairs(scorel) do
        if score > highest then
           leader, highest = name, score
        end
    end
    return leader, highest
end
print (high(scores)) -- 将打印领导者的名称和得分。
local leader, record = high(scores)
print (leader) -- 这将只打印冠军的名称。

如果每个人的得分都相同,您的算法将不会选择领导者,但也许这正是您想要的。 更新:分裂领导力:

function high(scorel)
    local record, leaders = 0, {}
    for name, score in pairs(scorel) do
        if score > record then
           record = score
           leaders = {name}
        elseif score == record then
           table.insert (leaders, name)
        end
    end
    return leaders, record
end
local leaders, record = high(score)
if #leaders > 0 then
    print ('最高得分(' .. tostring(record) .. ')属于' .. concat (leaders, ', '))
end
2020-10-15 06:50:06