Search code examples
luatostringmetatable

__tostring in custom classes Lua


The following code should print 'hello', however it is printing the memory location of the table (i.e. 'table: 052E67D0'). Please, explain what I'm missing here.

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)

Update

Tried doing this instead:

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)

which worked. This seems weird because, to me, self in constructor and TestClass: refer to the same table.


Solution

  • Your TestClass:new takes two arguments and you call it with just one when you create t.

    Change:

    local t = TestClass.new{}
    

    to:

    local t = TestClass:new{}
    

    Thanks to that self in this TestClass:new call is now reference to TestClass rather than to empty table which was (most likely) meant to be the new instance of the class.

    In case of doubts please refer to Lua Reference Manual §3.4.10 or this stackoverflow question.