Skip to content

Printing with metatable's "__tostring" if userdata has it? #38

Open
@eliasdaler

Description

@eliasdaler

Hello. First of all, I want to thank you for a wonderful lib that I've used for several years now.

I've got an idea. Sometimes it's convenient to add "__tostring" to userdata's metatable so that it's printable in Lua. For example, if I bind my C++ 2D Vector class, it then can be easily printed like this:

v = Vector2f.new(10, 20) -- create instance of C++ Vector
print(tostring(v)) -- prints "(10, 20)"

But when I print it with inspect, I get:
<userdata 1>

But what if inspect printed something like this if __tostring is present in userdata's metatable?

<userdata 1, tostring = "(10, 20)">

And instead of getting output like this:

{
  room = {
    areaName = "forest",
    size = <userdata 1>
  }
}

I'll be able to get this:

{
  room = {
    areaName = "forest",
    size = <userdata 1, tostring="(10,20)">
  }
}

... Which will greatly help me when debugging some tables.
Another possibility is to make inspect write tables like this:

{
  room = {
    areaName = "forest",
    size = <userdata 1> -- (10, 20)
  }
}

Maybe this can be turned on and off with options if you don't like this behavior to be present by default. I can make a PR with my implementation if you agree that this might be a good feature to have.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions