Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Lua 仅向表中添加10个值_Lua - Fatal编程技术网

Lua 仅向表中添加10个值

Lua 仅向表中添加10个值,lua,Lua,如何最多向表中添加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(na

如何最多向表中添加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()
//upd:也许是它的固定用户名

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

我建议您使用Lua的哈希表,
v.name
v.score
v[1]
v[2]
更容易阅读

函数
表.HasValue
不存在。你必须自己写

如果只想打印前十个元素,则只应在前十个元素上进行迭代(如果小于十个元素,则迭代到表的长度)

Lua中的行注释以
--
开头,而不是
/

local scoretbl = {}

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

local function AddToTable(name, score)
    -- Walk the whole table to find whether a name exists
    for i,v in ipairs(scoretbl) do
        if v.name == name then
            -- if the record is present, update it
            scoretbl[i].score = score
            return
        end
    end
    -- Insert new record
    table.insert(scoretbl, { name = name, score = score })
end

AddToTable('User 55', 5454) -- 11 users
AddToTable('User 55', 5454) -- check: only one username in table
AddToTable('User 32', 5454) -- 12 users

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()

若值从用户处更改,那个么表中的值不会更改吗?请看:我修改了:@Gigabait更新答案中的代码将更新现有记录。