Lua实战之table.remove

Description

local tbl1 = {1, 2, 2, 3, 3, 3, 4, 5, 5, 5, 6}

local tbl2 = {1, 2, 3, 3, 5, 6}

删除tbl1中存在于tbl2中的元素,使删除之后tbl1的值为:{2, 3, 4, 5, 5}

Implemention

local LogManager = require("LogManager")

local tbl1 = {1, 2, 2, 3, 3, 3, 4, 5, 5, 5, 6}
local tbl2 = {1, 2, 3, 3, 5, 6}

for _, v in pairs(tbl2) do
    for i = #tbl1, 1, -1 do  -- 倒着删
        if v == tbl1[i] then
            table.remove(tbl1, i)
            break  -- 跳出内层循环
        end
    end
end

LogManager:dump(tbl1, "tbl1")

--[[
- "tbl1" = {
-     1 = 2
-     2 = 3
-     3 = 4
-     4 = 5
-     5 = 5
- }
]]

 

你可能感兴趣的:(#,Lua,Exercise,Lua使用笔记)