只向表中添加10个值

如何只向表中添加最多10个用户? 因为我在txt中保存scoretbl,并且该文件有超过100行:/所以我只想保存10个用户。 我不知道如何检查表中是否存在用户名,以及是否添加此用户或不添加此用户名并将其添加到表中? 例如:

local scoretbl = {}
local num = 0
for i=1, 10 do
    table.insert(scoretbl,{'Name '..i, 100 + num})
    num = num + 100
end

local function AddToTable(name, score)
    if table.HasValue(scoretbl,name) then return end // hmm its not work ?
        table.insert(scoretbl,{name, score})
end

AddToTable('User 55', 5454)// 11 user
AddToTable('User 55', 5454)// check: only one username in table

AddToTable('User 32', 5454)// 12 user

local function ShowOnly10()
table.sort( scoretbl, function( a, b ) return a[2] > b[2] end )

//table.remove(scoretbl,#scoretbl) remove last index in table, if i need only 10 value, i need delete in cycle ?

    for k, v in pairs(scoretbl) do
        print(k ,v[1], v[2])
    end
end
ShowOnly10()

// 更新:也许修复用户名?

local function AddToTable(name, score)
    for k, v in pairs(scoretbl) do
        if v[1] == name then return false end
    end
    table.insert(scoretbl,{name, score})
end
点赞
用户1944004
用户1944004

我建议您使用 Lua 的 hashtable,v.namev.scorev[1]v[2] 更易于阅读。

函数table.HasValue不存在。您需要编写自己的函数。

当您只想打印前十个元素时,应仅迭代前十个元素(如果长度小于十个元素)。

在 Lua 中,行注释以 -- 开始,而不是 //

local scoretbl = {}

for i = 1,10 do
    table.insert(scoretbl, { name = 'Name '..i, score = 100*i })
end

local function AddToTable(name, score)
    -- 遍历整个表格以确定是否存在该名称
    for i,v in ipairs(scoretbl) do
        if v.name == name then
            -- 如果记录存在,则更新它
            scoretbl[i].score = score
            return
        end
    end
    -- 插入新记录
    table.insert(scoretbl, { name = name, score = score })
end

AddToTable('User 55', 5454) -- 11个用户
AddToTable('User 55', 5454) -- 检查:表中只有一个用户名
AddToTable('User 32', 5454) -- 12个用户

local function ShowOnly10()
    table.sort(scoretbl,function(a,b) return a.score > b.score end)

    for i = 1,math.min(#scoretbl,10) do
        print(i, scoretbl[i].name, scoretbl[i].score)
    end
end

ShowOnly10()
2018-05-30 07:04:32