Provide pushLuaUDObject() to return an existing LuaUDObject from C


Is there any simple-ish way to push a LuaUDObject* onto the lua stack from C code? I have one acquired via pd->lua->getArgObject() but I can't use pd->lua->pushObject() because that would create a new LuaUDObject and therefore two retain counters for the same object in memory.

It looks like there isn't a way to do this so I'm moving this post to the features requests.

Basically we would need something like:

// -- Pushes the given LuaUDObject onto the stack,
void playdate->lua->pushLuaUDObject(LuaUDObject*);

On the Lua side of pushObject we have a weak table that maps C pointers to their Lua wrappers, so that we can return the existing LuaUDObject. You just have to make sure you retain it if you hold a reference to it on the C side.

Someone pointed this out but it doesn't seem to work for me when receiving any Lua SDK objects in my C code:

const char* class_name;
int item_type = pd->lua->getArgType(2, &class_name);
DM_LOG("Found object '%s'.", this->class_name);
LuaUDObject* l_object = NULL;
void* object = pd->lua->getArgObject(2, (char*)class_name, &l_object);
DM_LOG("%p %p", object, l_object);
void* new_l_object = pd->lua->pushObject(object, (char*)this->class_name, 0);
DM_LOG("   %p", new_l_object);

When passing a, for example, new_l_object is not the same as l_object.

Is it possible that the SDK's objects are not added to this table?

Dang, sorry. I'd forgotten that's a 1.13 fix. I pushed that MR in September. :sob:

We'll get that out soon!

We'll get that out soon!

That's great news. I'll add that to my interop Lua/C Array class then.

pushObject now correctly returns the LuaUDObject* in 1.13. Thank you! :pray:t2:

It would still be useful to add something like pushLuaUDObject() though in order to save the lookup time if the user already has a valid LuaUDObject* save up somewhere...

The problem is you can't tell Lua "hey, here's a pointer to an object, put this on the stack", you have to get the reference from inside Lua. So we'd still need a lookup table there from the LuaUDObjects to the userdatas containing them. We could add a hack for that since we know LuaUDObjects are always contained in userdata, but I hesitate to make a change like that down in the Lua internals.

Oh I didn't realize that. I thought that the LuaUDObject* was the LUA wrapper for the user object that could be pushed right onto the stack (since that's the pointer you use to tell Lua to retain the object when needed).

I guess I don't know enough of the internals behind the scenes.