下面的几个函数是学习工作中,比较常用的工具函数:
-----整数下标的table,如果不连续时,使用---迭代器
function PairsByKeys( t, f )
local a = {}
for n in pairs(t) do
table.insert( a, n)
end
table.sort( a, f)
local i = 0
return function()
i = i + 1
return a[i],t[a[i]]
end
end
--常量表
function TabConst( _table )
local Const = function ( _table )
local mt =
{
__index = function (t,k)
if type(_table[k]) == "table" then
_table[k] = TabConst(_table[k])
end
return _table[k]
end,
__newindex = function (t,k,v)
print(debug.traceback())
end
}
return mt
end
local t = {}
setmetatable(t, Const(_table))
return t
end
function DeepCopy(object)
-- 需要深拷贝的对象
local lookup_table = {}
local function _copy(object)
if type(object) ~= "table" then
return object
elseif lookup_table[object] then
return lookup_table[object]
end
local new_table = {}
lookup_table[object] = new_table
for index, value in pairs(object) do
new_table[_copy(index)] = _copy(value)
end
return setmetatable(new_table, getmetatable(object))
end
return _copy(object)
end