Lua tostring元方法

Lua__tostring 元方法用于修改表的输出行为。

案例

Lua __tostring 元方法的使用

#!/usr/bin/lua print("haicoder(www.haicoder.net)\n") mytable = setmetatable({ 10, 20, 30 }, { __tostring = function(mytable) sum = 0 for k, v in pairs(mytable) do sum = sum + v end return "The sum is " .. sum end }) print(string.format("mytable = %s", mytable))

程序运行后,控制台输出如下:

07_Lua tostring元方法.png

我们自定义了 __tostring 元方法,用于自定义输出。

Lua tostring元方法总结

在 Lua 中 __tostring 元方法用于修改表的输出行为。