lua 数组去重
-- bArray = true 会把 t 当数组(连续的数字 key) -- 默认是当作“对象(key可以不是数字)” -- 或理解为是否保留原来的 key function table.unique(t, bArray) local check = {} local n = {} local idx = 1 for k, v in pairs(t) do if not check[v] then if bArray then n[idx] = v idx = idx + 1 else n[k] = v end check[v] = true end end return n end --[[ > local a = {1,3,2,3,4} > local b = table.unique(a) > for k,v in pairs(b) do print(k,v) end 1 1 2 3 3 2 5 4 ]]
lua table map方法
function table.map(t, fn) local n = {} for k, v in pairs(t) do local item = fn(v, k, t) table.insert(n, item) end return n end --[[ > local a = {1,3,2} > local b = table.map(a, function(v) return v .. '-' .. v end) > for k,v in pairs(b) do print(k,v) end 1 1-1 2 3-3 3 2-2 ]]
function table.filter(t, fn) local n = {} for k, v in pairs(t) do local item = fn(v, k, t) if item then table.insert(n, v) end end return n end --[[ > hyper = {'control', 'option', 'shift', 'command'} > hyper = table.filter(hyper, function(v) return v ~= 'shift' end) > for _,v in pairs(hyper) do print(v) end control option command ]]