我有一个关于 Lua 元表的问题。我听过并查过它们,但我不明白如何使用它们以及它们的用途。
最佳答案
元表是在特定条件下调用的函数。 以元表索引“__newindex”(两个下划线)为例,当您为其分配一个函数时,每当您向表添加新索引时都会调用该函数,例如;
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";
输出:
Attention! Index "Hey" now contains the value 'Dog' in table: 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.
我希望这能澄清问题,如果您需要更多示例,click here .
关于function - 元表如何工作以及它们的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4250556/