Lua 中自定义类中的 __tostring 方法

以下代码应该会打印出 'hello',但实际它却打印出表的内存地址(即 'table: 052E67D0')。请解释我在这里错过了什么地方。

TestClass = {}

function TestClass:new(o)
    o = o or {}
    setmetatable(o, self)
    self.__index = self
    return o
end

function TestClass:__tostring()
    return "hello"
end

local t = TestClass.new{}

print(t)

更新

试过用以下代码代替:

TestClass = {}

function TestClass:new(o)
    o = o or {}
    setmetatable(o, self)
    self.__index = self
    self.__tostring = function() return "hello" end
    return o
end
local t = TestClass.new{}

print(t)

这样做可以实现目的。但对我来说,这看起来很奇怪,因为在构造函数中的 'self' 和 'TestClass:' 指的应该是同一个表。

点赞
用户4567755
用户4567755

你的 TestClass:new 接受两个参数,在创建 t 的时候你只给了一个参数。

修改:

local t = TestClass.new{}

为:

local t = TestClass:new{}

多亏这个修改,现在 TestClass:new 中的 self 参数是指向 TestClass 而不是指向一个空表(很可能是想创建类的新实例)。

如果有疑问,请参阅Lua参考手册§3.4.10这个stackoverflow问题

2019-07-02 13:11:27