3

Luaメタテーブルについて、この1つの質問があります。聞いて調べましたが、使い方や使い方がわかりません。

4

4 に答える 4

11

メタテーブルは、特定の条件下で呼び出される関数です。メタテーブル インデックス "__newindex" (2 つのアンダースコア) に関数を割り当てると、テーブルに新しいインデックスを追加するたびにその関数が呼び出されます。

table['wut'] = 'lol';

これは、'__newindex' を使用したカスタム メタテーブルの例です。

ATable = {}
setmetatable(ATable, {__newindex = function(t,k,v)
    print("Attention! Index \"" .. k .. "\" now contains the value \'" .. v .. "\' in " .. tostring(t));
end});

ATable["Hey"]="Dog";

出力:

注意!インデックス「Hey」には、テーブルの値「Dog」が含まれるようになりました: 0022B000

メタテーブルは、テーブルが他のテーブルやさまざまな値とどのように相互作用するかを記述するためにも使用できます。

これは、使用可能なすべてのメタテーブル インデックスのリストです。

* __index(object, key) -- Index access "table[key]".
* __newindex(object, key, value) -- Index assignment "table[key] = value".
* __call(object, arg) -- called when Lua calls the object. arg is the argument passed.
* __len(object) -- The # length of operator.
* __concat(object1, object2) -- The .. concatination operator.
* __eq(object1, object2) -- The == equal to operator.
* __lt(object1, object2) -- The < less than operator.
* __le(object1, object2) -- The <= less than or equal to operator.
* __unm(object) -- The unary - operator.
* __add(object1, object2) -- The + addition operator.
* __sub(object1, object2) -- The - subtraction operator. Acts similar to __add.
* __mul(object1, object2) -- The * mulitplication operator. Acts similar to __add.
* __div(object1, object2) -- The / division operator. Acts similar to __add.
* __mod(object1, object2) -- The % modulus operator. Acts similar to __add.
* __tostring(object) -- Not a proper metamethod. Will return whatever you want it to return.
* __metatable -- if present, locks the metatable so getmetatable will return this instead of the metatable and setmetatable will error. 

これで問題が解決することを願っています。さらにいくつかの例が必要な場合は、 ここをクリックしてください

于 2010-11-22T22:27:46.113 に答える
4

Read http://www.lua.org/pil/13.html

于 2010-11-22T23:51:07.447 に答える
0

テーブルを文字列、関数、数値などの他のタイプと同じように扱うことができます。

于 2010-11-24T21:57:16.403 に答える
0

プロトタイプ パターンの高レベルで面白い読み物については、 http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.htmlをチェックしてください。これは、「何」に役立つ場合があります。

于 2010-11-25T21:43:47.990 に答える