Search code examples
printinglua

get the address of a lua object


When you print certain types in lua (such as functions and tables), you get the name of the type and an address, as below:

> tab = {}
> print(tab)
table: 0xaddress

I have created a simple class as below, and I would like to override the __tostring method similarly. How do I get the address of the object that I want to print?

Here's my class. I would like print(pair) to print out Pair: 0xaddress. Obviously this is a trivial example, but the concept is useful:

Pair = {}
Pair.__index = Pair

function Pair.create()
 local p = {}
 setmetatable(p, Pair)
 p.x = 0
 p.y = 0
 return p
end

function Pair:getx()
 return self.x
end

function Pair:gety()
 return self.y
end

function Pair:sety(iny)
 self.y=iny   
end

function Pair:setx(inx)
 self.x=inx
end

Solution

  • Here's a hokey way to do it:

    Pair.__tostringx = function (p)
        Pair.__tostring = nil    
        local s = "Pair " .. tostring(p)                                                                                                                                                                                                    
        Pair.__tostring = Pair.__tostringx
        return s
    end
    Pair.__tostring = Pair.__tostringx    
    
    > print(p)
    Pair table: 0x7fe469c1f900
    

    You can do more string manipulation inside Pair.__tostringx to get the format you want, e.g., to remove "table".