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 8368165
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T13:19:25+00:00 2026-06-09T13:19:25+00:00

I’ve been working with LuaPlus to expose the functionality of a module with a

  • 0

I’ve been working with LuaPlus to expose the functionality of a module with a scripting language. For that, LuaPlus has been really awesome but i’m stuck with the cleanup of my exposed objects because I don’t know how to handle the deletion of the lua object representing my c++ object so i can correctly free the c++ resource.

I’m using lua tables and metatables to represent cpp objects, passing the pointer to the cpp object as the lightuserdata parameter “__object” of the table, so i can do things like

function foo() 
  local p = MyCppObject:new()   //Create a cpp object and bind it to a table+metatable
  p:do_something()        //Correctly calls the cpp member function do_something
  ....
  (exits scope)           //No more references to p, so p is deleted.
 end

After the exit of the function (or some time later), i expected to get the call to the metatable method “__gc”, where i call the delete for the internal cpp object, but i don’t see my cpp callback being called at all. I tried forcing the the garbagecollection using lua’s function collectgarbage, called my function a ton of times to force lua to collect my objects and i can’t see my callback executing. On top of it, i see that the result of calling collectgarbage(“count”) decreases sometimes so something is getting deleted somewhere, but i don’t know what. I’ve checked the lua documentation and i don’t see what i’m doing wrong 🙁

Any comment is appreciated! Thanks!


Update: Added c++ code side + added local as Mud pointed out + sample of my test

I created this small sample of my program. The LuaShell object is simply a wrapper for the state + the loop of reading a command line and executing the string read from std::cin

#include <iostream>
#include "LuaPlus.h"
class Point
{
  private:
      int x_,y_;
  public:
  Point(): x_(0), y_(0){}
  Point(int a, int b): x_(a), y_(b){}

  ~Point() {std::cout << "Point "<< x_ << ","
                      << y_ << "being deleted" << std::endl;} 

  int x() const  { return x_;} 
  int y() const  { return y_;}     
};

LuaPlus::LuaObject metatable;

int new_point( LuaPlus::LuaState* state)
{
  LuaPlus::LuaStack args(state);
  //std::cout << "Creating point!!" << std::endl;
  float x = 0, y = 0;
  if ( args.Count() == 3)
  {
      if (args[2].IsNumber() && args[3].IsNumber())
      {
          x = args[2].GetFloat();
          y = args[3].GetFloat();
      }
  }

  Point* p = new Point(x,y);
  LuaPlus::LuaObject lua_obj = state->CreateTable();
  lua_obj.SetLightUserData("__object", p);
  lua_obj.SetMetaTable( metatable );

  return 1;
}

int my_gc_event( LuaPlus::LuaState* state) 
{
  std::cout << "Calling gc_event from lua" << std::endl;
  return 0;
}

int main()
{

  /* Creating the object that holds the Lua interpreter as well as 
   * the command line
   */ 
  LuaShell::Shell shell(true);
  LuaPlus::LuaObject globals = shell.get_state()->GetGlobals();

  metatable = globals.CreateTable("PointMetaTable");
  metatable.SetObject("__index", metatable);
  metatable.Register("new", new_point);
  metatable.Register("__gc",my_gc_event);
  metatable.RegisterObjectDirect("x", (Point*)0 ,&Point::x);
  metatable.RegisterObjectDirect("y", (Point*)0 ,&Point::y);
  globals.SetObject("Point", metatable);

  //Get into the read-command-line-until-quit loop.
  shell.run();
  return 0;
}

In the lua side, i run this to test.

? k,b = collectgarbage("count") print (k*1024) 
> 33761
? for it=1,1000000 do foo() end   
? k,b = collectgarbage("count") print (k*1024) 
> 75315
? collectgarbage()  
? k,b = collectgarbage("count") print (k*1024)
> 32363

As you see, there is “some” garbage collecting according to the lua runtime, but when i see the top report of my process the memory only goes up, and never down. Also i never see the message from the point destructor (expected as i’m not really calling it) or the one from inside “my_gc_event” (unexpected, because i’d think it got called at some point during the collectgarbage work).

Thanks again!

  • 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-06-09T13:19:26+00:00Added an answer on June 9, 2026 at 1:19 pm
    function foo() 
      p = MyCppObject:new()   //Create a cpp object and bind it to a table+metatable
      p:do_something()        //Correctly calls the cpp member function do_something
      ....
      (exits scope)           //No more references to p, so p is deleted.
    end
    

    p is global, so it doesn’t leave scope when foo returns. You need to use the keyword local if you want it lexically scoped to that function.

    lightuserdata parameter […] i expected to get the call to the metatable method “__gc”

    Lightuserdata are not garbage collected. That may not be related to your problem (I don’t know how LuaBind works), but I thought it worth mentioning.


    Response to comments:

    I wrote the following test, which creates a single byte, do-nothing userdata type which has only a __gc in it’s metatable:

    #include "lauxlib.h"
    
    static int foo_gc (lua_State* L) { 
       puts("__gc called");
       return 0; 
    }
    
    static int foo_new (lua_State* L) { 
       lua_newuserdata(L, 1);
       luaL_getmetatable(L, "foo");
       lua_setmetatable(L, -2);
       return 1;
    }
    
    int __declspec(dllexport) __cdecl luaopen_luagc (lua_State* L) {
       // create foo type
       static const struct luaL_reg foo[] = {
          { "__gc",        foo_gc       },
          NULL, NULL
       };
       luaL_newmetatable(L, "foo");
       luaL_openlib(L, NULL, foo, 0);
    
       // create constructor
       lua_register(L, "foo", foo_new);
       return 0;
    }
    

    If I then run the following test:

    require 'luagc'
    
    for i=1,5 do
       foo()
    end
    
    collectgarbage("collect")
    

    The output is:

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

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I want to count how many characters a certain string has in PHP, but
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I'm working with an upstream system that sometimes sends me text destined for HTML/XML
I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
Basically, what I'm trying to create is a page of div tags, each has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function

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.