metatables如何工作以及它们用于什么?

Stu*_*RIO 2 lua programming-languages function roblox

我有一个关于Lua metatables的问题.我听到并查看了它们,但我不明白如何使用它们以及用于什么.

小智 9

metatables是在某些条件下调用的函数.获取metatable索引"__newindex"(两个下划线),当您为此指定一个函数时,在向表中添加新索引时将调用该函数,例如:

table['wut'] = 'lol';
Run Code Online (Sandbox Code Playgroud)

这是使用'__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";
Run Code Online (Sandbox Code Playgroud)

输出:

注意!索引"Hey"现在包含表中的值'Dog':0022B000

元表也可用于描述表应如何与其他表交互,以及不同的值.

这是您可以使用的所有可能的metatable索引的列表

* __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. 
Run Code Online (Sandbox Code Playgroud)

我希望这可以解决问题,如果您需要更多示例, 请单击此处.

  • 请注意,您的示例取决于用户.除非你在`__newindex`元方法的某个地方执行`t [k] = v`,否则值不会进入表中. (3认同)