【问题标题】:How to assign number next to variable if variable is part of table? Lua如果变量是表的一部分,如何在变量旁边分配数字?卢阿
【发布时间】:2014-03-13 06:41:13
【问题描述】:
  • 如果 player1 还活着,则表 mvp 的当前输出:

    “播放器1,播放器2,播放器3,播放器1,播放器2,播放器1,播放器2,播放器3,播放器1”

  • 如果 player1 还活着,表 mvp 的期望输出:

    “播放器1 - 4,播放器2 - 3,播放器3 - 2”

我在问如何缩短输出。 @余浩,干得好!只是我不善于解释我的问题):对不起,我编辑了我的问题


【问题讨论】:

  • 并不是每个人都可以访问此类链接(我的雇主阻止了 pastebin 等)。

标签: lua lua-table


【解决方案1】:

对于已编辑的问题,您可以将表项存储在一个集合中,其计数如下:

mvp = {"player1", "player2", "player3", "player1", "player2", "player1", "player2", "player3", "player1"}

local t = {}
for k, v in ipairs(mvp) do
    t[v] = (t[v] or 0) + 1
end
local count = {}
local index = 1
for k, v in pairs(t) do
    count[index] = k .. " - " .. v
    index = index + 1
end

str = table.concat(count, ", ")
print(str)

输出:player1 - 4, player3 - 2, player2 - 3

注意名字没有排序,因为pairs()的使用,如果名字需要排序的话,你需要做一些额外的工作。

【讨论】:

  • 干得好!但是我在解释我的问题时很糟糕,我想知道你是否可以再看一遍?我编辑了。给您带来的不便,我深表歉意。
【解决方案2】:

试试这个:您可以直接使用mvpmvpp 表来计算出现次数;然后使用string.format根据需要格式化输出,但是由于可以有多个播放器,因此您可以使用table.concat组合多个播放器的输出;最后你输入ui

function output(scores, x, y)
    local out  = {}
    for player, score in scores do 
        table.insert(out, string.format("%s - %s", player, score))
    end
    ui.addTextArea(1,"<a href='event:closee'> ".. table.concat(out, ";") .. " </a>", NIL, 6, x,y, 50,0x1C3C41,0x1C3C41,0.9,true)
end

function eventLoop(time)
    local mvp = {}
    local mvpp = {}

    if time < 120000 then
        for name, player in pairs(tfm.get.room.playerList) do
            if not player.isDead then
                if TeamOne[name] then
                    mvp[name] = (mvp[name] or 0) + 1
                end
                if TeamTwo[name] then
                    mvpp[name] = (mvpp[name] or 0) + 1
                end
            end
        end
    end
    -- now mvp = {player1 = 200, player3 = 50} for example
    output(mvp,    6, 308)
    output(mvpp, 406, 208)
end

实际上还有几个参数要传递给output()(比如addTextArea()href 名称的第一个参数),但你明白了。

【讨论】:

  • 哦,有趣!感谢您的帮助!
猜你喜欢
  • 2020-12-27
  • 2020-10-28
  • 2019-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-18
  • 1970-01-01
  • 2020-03-12
相关资源
最近更新 更多