Search code examples
lualua-table

Lua - get table hex identifier


I want to know how to get the table hex id. I know that doing:

local some_var = {}
print (some_var)

the result is (for instance):

table: 0x21581c0

I want the hex without the table: string. I know that maybe some of you suggest me to make a regular expression (or something similar) to remove those chars, but I want to avoid that, and just get the 0x21581c0

Thanks


Solution

  • In the standard implementation, there is the global 'print' variable that refers to a standard function that calls, through the global variable 'tostring', a standard function described here. The stanard 'tostring' function is the only way to retrieve the hexadecimal number it shows for a table.

    Unfortunately, there is no configuration for either of the functions to do anything differently for all tables.

    Nonetheless, there are several points for modification. You can create you own function and call that every time instead, or point either of the the global variables print or tostring to you own functions. Or, set a __tostring metamethod on each table you need tostring to return a different answer for. The advantage to this is it gets you the format you want with only one setup step. The disadvantage is that you have to set up each table.

    local function simplifyTableToString(t)
       local answer = tostring(t):gsub("table: ", "", 1)
       local mt = getmetatable(t) 
       if not mt then
          mt = {}
          setmetatable(t, mt)
       end
       mt.__tostring = function() return answer end
    end
    
    local a = {}
    local b = {}    
    print(a, b)
    simplifyTableToString(a)
    print(a, b)