Luaで良く作る関数 ~table編~

table.empty

-- テーブルが空かどうかの判定
-- 引数にnilを渡しても「空」とみなす。
function table.empty(tbl)
	if tbl==nil then return true end
	return not next (tbl)
end

table.elemn

-- テーブルに実際に存在する要素数(=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

table.in_key

-- 対象のテーブルのキーに、指定の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

table.in_value

-- 対象のテーブルの値に、指定の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

table.map

-- 対象のテーブルの各要素に対して、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乗した新たなテーブルを得る

table.dcopy

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

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)

table.scopy

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