lua - 从 Lua 表中删除特定条目
问题描述
我正在插入这样的表格
Admin = {}
table.insert(Admins, {id = playerId, Count = 0})
这很好用。
我现在如何从该表中删除该特定管理员?
以下不起作用,我确定它是因为 ID 存储在表内部的数组中,但是我将如何访问它呢?
table.remove(Admins, playerId)
基本上,我想从表 Admins 中删除我输入的 ID == playerId。
解决方案
有两种方法可以从表中删除条目,这两种方法都是可以接受的:
1. myTable[index] = nil
从给定索引中删除一个条目,但通过维护索引在表中添加一个洞
local Admins = {}
table.insert(Admins, {id = 10, Count = 0})
table.insert(Admins, {id = 20, Count = 1})
table.insert(Admins, {id = 30, Count = 2})
table.insert(Admins, {id = 40, Count = 3})
local function removebyKey(tab, val)
for i, v in ipairs (tab) do
if (v.id == val) then
tab[i] = nil
end
end
end
-- Before
-- [1] = {['Count'] = 0, ['id'] = 10},
-- [2] = {['Count'] = 1, ['id'] = 20},
-- [3] = {['Count'] = 2, ['id'] = 30},
-- [4] = {['Count'] = 3, ['id'] = 40}}
removebyKey(Admins, 20)
-- After
-- [1] = {['Count'] = 0, ['id'] = 10},
-- [3] = {['Count'] = 2, ['id'] = 30},
-- [4] = {['Count'] = 3, ['id'] = 40}
2. table.remove(myTable, index)
从给定索引中删除条目并重新编号索引
local function getIndex(tab, val)
local index = nil
for i, v in ipairs (tab) do
if (v.id == val) then
index = i
end
end
return index
end
local idx = getIndex(Admins, 20) -- id = 20 found at idx = 2
if idx == nil then
print("Key does not exist")
else
table.remove(Admins, idx) -- remove Table[2] and shift remaining entries
end
-- Before is same as above
-- After entry is removed. Table indices are changed
-- [1] = {['id'] = 10, ['Count'] = 0},
-- [2] = {['id'] = 30, ['Count'] = 2},
-- [3] = {['id'] = 40, ['Count'] = 3}
推荐阅读
- flutter - 是否可以在颤动时每 x 秒调用一次函数?
- json - 如何遍历未知的 JSON 数据/对象?
- flutter - Slidable Widget 滑动时显示垂直线 - Flutter_slidable
- c - Mips如何计算整数中的唯一数字
- android - 在项目中添加 Monogame 的正确方法
- presto - 带有冒号 (:) 的 Amazon Athena 分区不起作用
- google-apps-script - 谷歌表格权限授权
- python - 如何根据 Python 中的前一个元素将新元素添加到列表中?
- php - 防止 laravel morphMany 将 id 转换为整数
- powershell - Powershell Test-NetConnection 在循环脚本中返回 False