3

我有一个关于 Lua 元表的问题。我听到并查找了它们,但我不明白如何使用它们以及用于什么目的。

4

4 回答 4

11

元表是在特定条件下调用的函数。以元表索引“__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";

输出:

注意力!索引“嘿”现在包含表中的值“狗”: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

阅读http://www.lua.org/pil/13.html

于 2010-11-22T23:51:07.447 回答
0

有关原型模式的高层次、有趣的阅读,请查看http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html。这可能会帮助您解决“什么”问题。

于 2010-11-25T21:43:47.990 回答
0

它们允许将表格视为其他类型,例如字符串、函数、数字等。

于 2010-11-24T21:57:16.403 回答