Get lua object address

When you print specific types in lua (e.g. functions and tables), you get the type name and address, as shown below:

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

I created a simple class as shown below, and I would like to override the __tostring method __tostring same way. How to get the address of the object I want to print?

Here is my class. I would like to print(pair) print 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) px = 0 py = 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 
+6
source share
2 answers

Here is the hockey way to do this:

 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 operations inside Pair.__tostringx to get the format you want, for example, to delete a β€œtable”.

+7
source

I think that __tostring() , which prints table: 0xaddress , is not actually implemented in direct Lua. I looked around the bunch, but the only way I could think was not exactly what you were thinking. I added a function to the Pair class called toString, which uses the standard __tostring() string to get a normal string, then takes out a β€œtable” and puts it in β€œpairs”.

 function Pair:toString() normalPrint = tostring(self) return ("Pair:" .. normalPrint:sub(7)) end pair = Pair.create() print(pair:toString()) 

Then you call pairs: toString () to get the correctly formatted output. You cannot do this by overriding __tostring because it will be difficult for you to access super __tostring, and if you call __tostring pairs, the stack overflow comes from recursion.

+1
source

Source: https://habr.com/ru/post/927203/


All Articles