lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

> > How do you pass your userdata object into Lua calls?  That is, say I 
> > have C++ code that wants to call a function like:
> > 
> > int doSomething(MyObject* obj);

> Yep, in my case the number of calls like this is relatively minimal.  I
> do indeed just push a newuserdatabox() every time.
> I haven't found this to be a problem for what I'm doing, but I can see
> that it could become prohibitive in other applications.

In older versions of Lua, we had lua_pushuserdata, which coalesced all
userdata pointers as a single object. You could push it as many times as
you wanted.

If it does become a problem, you could try to reproduce the old behaviour
in this new context, by keeping a table with weak keys mapping pointer
values into their associated userdata objects.

Then, an untested version of lua_oldpushuserdata could look like this:

    void lua_oldpushuserdata(lua_State *L, void *pointer)
        lua_getref(L, someweakkeytable);
        lua_pushlstr(L, pointer, sizeof(pointer));
        lua_gettagle(L, -2);
        if (lua_isnil(L, -1)) {
            lua_pop(L, 1);
            lua_newuserdatabox(L, pointer);
            lua_pushlstr(L, pointer, sizeof(pointer));
            lua_pushvalue(L, -2);
            lua_settable(L, -2);
            lua_remove(L, -2);
            /* WARNING: here you would have to increment your refcount! 
               and set your eventtable again */

Just a thought.