metatable(MetaMethod)


POINT MetaMethod を利用して, Lua を拡張(カスタマイズ)できる。


自分で作成した型を調べる


type( data ) == "table" if ( getmetatable( g ) == rgbmeta ) then print("custom data"); end


配列の上限値を設定する


( MetaMethod を利用することで テーブル要素の参照をカスタマイズする __index, __newindex を上書きする. __index : val = tbl["name"]; // 参照. __newindex : tbl["name"] = "foo"; // 代入 MetaMethod の定義中に, MetaMethod を呼ぶのを防ぐのは, rawget, rawset() -- rawget( tbl, idx ); val = tbl[idx] -- rawset( tbl, idx, val ); tbl[idx] = val -- -- MetaTbl -- この tbl EventKey に対して OverWrite 関数をセットする. tblTest = { limit = 3 }; -- -- tbl を参照する [] 演算子を overwrite する -- tblTest.__index = function( t, idx ) if ( idx > tblTest.limit ) then error("invalid dana idx"); end return rawget( t, idx ); end -- メタテーブルをセットする。 tt = {} setmetatable( tt, tblTest ); -- テスト print( tt[10] );