-- テーブルに実際に存在する要素数(=num of elements)
-- 「#」や「table.getn」「table.maxn」ではテーブルの要素数は調べられないので必要となる。
function table.elemn(tbl)
local n = 0
for _ in pairs (tbl) do
n = n + 1
end
return n
end
-- 対象のテーブルの各要素に対して、func(key, value)を実行し、関数実行結果を格納する。
-- 元のテーブルの値は変化せず、新たなテーブルが返される。
function table.map(tbl, func)
local ret_tbl = {}
for k, v in pairs (tbl) do
ret_tbl[k] = func (k, v)
end
return ret_tbl
end
使い方
local tbl = {1,2,k=4 }
local tbl2 = table.map( tbl , function(k, v) return v*v end ) -- 全ての要素を2乗した新たなテーブルを得る
function table.dcopy(tbl)
local orig_type = type(tbl)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, tbl, nil do
copy[table.dcopy(orig_key)] = table.dcopy(orig_value)
end
setmetatable(copy, table.dcopy(getmetatable(tbl)))
else -- number, string, boolean, etc
copy = tbl
end
return copy
end
test.lua
local a = {1, 2, 3, { b=3,d=4, {c=a} } }
local b = {__iter = "abc", e = 33 }
setmetatable(a, b)
local c = table.dcopy(a)
function table.scopy(tbl)
local orig_type = type(tbl)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in pairs(tbl) do
copy[orig_key] = orig_value
end
else -- number, string, boolean, etc
copy = tbl
end
return copy
end