*Luaで良く作る関数 ~table編~ [#x86ba688]

-[[table.empty>#table_empty]]
-[[table.elemn>#table_elemn]]
-[[table.in_key>#table_in_key]]
-[[table.in_value>#table_in_value]]
-[[table.map>#table_map]]
-[[table.dcopy>#table_deeepcopy_recursive]]
-[[table.scopy>#table_shallowcopy]]

&aname(table_empty);
**table.empty [#v0d29c8d]
#sh(lua){{
-- テーブルが空かどうかの判定
-- 引数にnilを渡しても「空」とみなす。
function table.empty(tbl)
	if tbl==nil then return true end
	return not next (tbl)
end
}}

&aname(table_elemn);
**table.elemn [#p6fb257c]
#sh(lua){{
-- テーブルに実際に存在する要素数(=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
}}



&aname(table_in_key);
**table.in_key [#qe875447]
#sh(lua){{
-- 対象のテーブルのキーに、指定のkeyが存在するかどうか。
function table.in_key (tbl, key)
	for k, v in pairs (tbl) do
		if k==key then return true end
	end
	return false
end
}}


&aname(table_in_value);
**table.in_value [#zc99510e]
#sh(lua){{
-- 対象のテーブルの値に、指定のvalが存在するかどうか。
function table.in_value (tbl, val)
	for k, v in pairs (tbl) do
		if v==val then return true end
	end
	return false
end
}}


&aname(table_map);
**table.map [#vf1c03dc]
#sh(lua){{
-- 対象のテーブルの各要素に対して、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
}}

-使い方

#sh(lua){{
local tbl = {1,2,k=4 }
local tbl2 = table.map( tbl , function(k, v) return v*v end ) -- 全ての要素を2乗した新たなテーブルを得る
}}


&aname(table_deeepcopy_recursive);
**table.dcopy [#za5236fa]
- テーブルの再帰的なディープコピー(deepcopy)を新たなテーブルとして返します。~
メタテーブルもコピーされます。

#sh(lua){{
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

#sh(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)
}}


&aname(table_shallowcopy);
**table.scopy [#t1429da5]
- テーブルのシャロウコピー(shallowcopy)を新たなテーブルとして返します。~
メタテーブルはコピーされません。

#sh(lua){{
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

}}


トップ   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS