lua table函数补充 lua table的扩展
lua table函数补充
-- lua table扩展 -- 返回table大小 table.size = function(t) local count = 0 for _ in pairs(t) do count = count + 1 end return count end --返回table的最大value table.maxn = function(t) local maxn = nil for _, v in pairs(t) do if nil == maxn then maxn = v end if maxn < v then maxn = v end end return maxn end --返回table的最小value table.minn = function(t) local min = nil for _, v in pairs(t) do if nil == min then min = v end if min > v then min = v end end return min end -- 判断table是否为空 table.empty = function(t) return not next(t) end -- 返回table索引列表 table.indices = function(t) local result = {} for k, v in pairs(t) do table.insert(result, k) end return result end -- 返回table值列表 table.values = function(t) local result = {} for k, v in pairs(t) do table.insert(result, v) end return result end -- 浅拷贝 table.clone = function(t, nometa) local result = {} if not nometa then setmetatable(result, getmetatable(t)) end for k, v in pairs (t) do result[k] = v end return result end -- 深拷贝 table.copy = function(t, nometa) local result = {} if not nometa then setmetatable(result, getmetatable(t)) end for k, v in pairs(t) do if type(v) == "table" then result[k] = table.copy(v, nometa) else result[k] = v end end return result end table.merge = function(dest, src) for k, v in pairs(src) do dest[k] = v end end table.random = function(tbl) local len = #tbl if len == 1 then return tbl end for i = 1, len do local ranOne = math.random(1, len+1-i) tbl[ranOne], tbl[len+1-i] = tbl[len+1-i],tbl[ranOne] end return tbl end table.contain = function(t, val) for _, v in pairs(t) do if v == val then return true end end return false end table.count = function(t, val) local cnt = 0 for _, v in pairs(t) do if v == val then cnt = cnt + 1 end end return cnt end table.sum = function(t) local s = 0 for _, v in pairs(t) do s = s + v end return s end table.sub = function(t, start, count) local st = {} for i = 1, count do table.insert(st, t[start+i-1]) end return st end table.findIdx = function(t, val) for k, v in ipairs(t) do if v == val then return k end end return -1 end table.removeVal = function(t, val) for k, v in ipairs(t) do if v == val then return table.remove(t, k) end end end --用val填充table table.fill = function(t, val, count) if not count then count = #t end for i = 1, count do t[i] = val end return t end table.shuffle = function(t) for i = #t, 2, -1 do local j = math.random(i) t[i], t[j] = t[j], t[i] end return t end