function - 元表如何工作以及它们的用途是什么?

标签 function lua programming-languages

我有一个关于 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/

相关文章:

MySQL - 可以调用函数来执行触发器操作吗?

java - Lua 在 Android 上是否与 Java 一样强大,或者有什么限制?

jquery - 修改一个简单的 jquery 函数来改变图像的不透明度

javascript - 如何发送不同的 ID 作为 JS 函数的参数?

Lua添加错误

hash - 哈希在编程中是如何工作的?

c - 向数千个文件添加 trec 格式标签

programming-languages - 是否有依赖非拉丁字母的编程语言?

C++ 在另一个函数中调用一个类函数

sockets - Lua连接redis服务器困难