Question: about Lua user data C API

I have some questions about Lua’s C API.

When you run the following code, the stacks appear to be inconsistent.
(Each time a line is executed, the number of stacks is printed.)

PlaydateAPI* api;
PRINT("%d", api->lua->getArgCount());  // -> 1
LuaUDObject* obj = api->lua->pushObject(ptr, "Test", 4);
PRINT("%d", api->lua->getArgCount());  // -> 3(?)
api->lua->pushInt(127);
PRINT("%d", api->lua->getArgCount());  // -> 4
api->lua->setObjectValue(obj, 4);
PRINT("%d", api->lua->getArgCount());  // -> 4(?)

The first one is the self at the time this function is called.

It then wraps a pointer with the user data.
I was hoping for a 2, but it was actually a 3. Is there anything more than user data piled up?

Then, stack the integers. This is a 4, as expected.

Call setObjectValue() to set the user data to the last integer.
I guessed from the manual that the stack top value would be set to the user data slot and removed from the stack, and stack-size will go to 3, but the result was still 4.

In this state, if the value is set to return 1 on the Lua side, 127 (integer) will be returned, and the user data cannot be returned.

I also couldn’t find an API to remove the stack value in the manual.

Have I missed or misunderstood something…?

Regards.

on SDK0.10.1

1 Like

pushObject() adding two items to the stack was a pretty dumb bug: the function first looks up the pointer in a cache table, and if the result is nil it creates a new userdata for it. But doesn’t clear the nil off the stack first, natch. I added a fix for that.

And you’re right, setObjectValue() shouldn’t leave the value on the stack because we don’t give you any way to remove it. I’ll fix that now! A workaround here is to push the object again so the userdata is at the top of the stack. It’ll reuse the userdata it created in the first pushObject() call.

1 Like