首页 文章

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

提问于
浏览
2

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

4 回答

  • 3

    它们允许表像其他类型一样对待,如字符串,函数,数字等 .

  • 0

    对于高级别,原型模式上的娱乐阅读检查http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html . 这可能会帮助您使用'what' .

  • 0

    metatables是在某些条件下调用的函数 . 获取metatable索引“__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";
    

    输出:

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

    如果你需要更多的例子,我希望这可以解决问题,click here .

  • 9

相关问题