Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 947179
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T23:02:40+00:00 2026-05-15T23:02:40+00:00

I’ve implemented my own class system and I’m having trouble with __tostring ; I

  • 0

I’ve implemented my own class system and I’m having trouble with __tostring; I suspect a similar issue can happen with other metamethods, but I haven’t tried.

(Brief detour: each class has a __classDict attribute, holding all methods. It is used as the class instances’ __index. At the same time, the __classDict’s __index is the superclass’ __classDict, so methods in superclasses are authomatically looked up.)

I wanted to have a “default tostring” behavior in all instances. But it didn’t work: the “tostring” behavior doesn’t “propagate” through subclasses correctly.

I’ve done this test exemplifying my issue:

mt1 = {__tostring=function(x) return x.name or "no name" end }
mt2 = {}
setmetatable(mt2, {__index=mt1})
x = {name='x'}
y = {name='y'}
setmetatable(x, mt1)
setmetatable(y, mt2)
print(x) -- prints "x"
print(mt2.__tostring(y)) -- prints "y"
print(y) -- prints "table: 0x9e84c18" !!

I’d rather have that last line print “y”.

Lua’s “to_String” behaviour must be using the equivalent of

rawget(instance.class.__classDict, '__tostring')

instead of doing the equivalent of

instance.class.__classDict.__tostring

I suspect the same happens with all metamethods; rawget-equivalent operations are used.

I guess one thing I could do is copying all the metamethods when I do my subclassing (the equivalent on the above example would be doing mt2.__tostring = mt1.__tostring) but that is kind of inelegant.

Has anyone fought with this kind of issue? What where your solutions?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T23:02:40+00:00Added an answer on May 15, 2026 at 11:02 pm

    Thanks to daurnimator’s comments, I think I found a way to make metamethods “follow” __index as I want them to. It’s condensed on this function:

    local metamethods = {
      '__add', '__sub', '__mul', '__div', '__mod', '__pow', '__unm', '__concat', 
      '__len', '__eq', '__lt', '__le', '__call', '__gc', '__tostring', '__newindex'
    }
    
    function setindirectmetatable(t, mt) 
      for _,m in ipairs(metamethods) do
        rawset(mt, m, rawget(mt,m) or function(...)
          local supermt = getmetatable(mt) or {}
          local index = supermt.__index
          if(type(index)=='function') then return index(t,m)(...) end
          if(type(index)=='table') then return index[m](...) end
          return nil
        end)
      end
    
      return setmetatable(t, mt)
    end
    

    I hope it is straightforward enough. When a new metatable is set, it initializes it with all metamethods (without replacing existing ones). These metamethods are prepared to “pass on” requests to “parent metatables”.

    This is the simplest solution I could find. Well, I actually found a solution that used less characters and was a bit faster, but it involved black magic (it involved metatable functions de-referencing themselves inside their own bodies) and it was much less readable than this one.

    If anyone finds a shorter, simpler function that does the same, I’ll gladly give him the answer.

    Usage is simple: replace setmetatable by setindirectmetatable when you want it to “go up”:

    mt1 = {__tostring=function(x) return x.name or "no name" end }
    mt2 = {}
    setmetatable(mt2, {__index=mt1})
    x = {name='x'}
    y = {name='y'}
    setmetatable(x, mt1)
    setindirectmetatable(y, mt2) -- only change in code
    print(x) -- prints "x"
    print(mt2.__tostring(y)) -- prints "y"
    print(y) -- prints "y"
    

    A little word of warning: setindirectmetatable creates metamethods on mt2. Changing that behavior so a copy is made, and mt2 remains unaltered, should be trivial. But letting them set up by default is actually better for my purposes.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm having trouble keeping the paragraph square between the quote marks. In firefox the
I have a jquery bug and I've been looking for hours now, I can't
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
Does anyone know how can I replace this 2 symbol below from the string
I am doing a simple coin flipping experiment for class that involves flipping a
I'm working with an upstream system that sometimes sends me text destined for HTML/XML
That's pretty much it. I'm using Nokogiri to scrape a web page what has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.