`pd->sprite->newSprite()` in registered class constructor throws `bad argument #1 to 'newObject' (image or tilemap)`

This is in SDK 2.0.0.

I've defined a class in C that I register with registerClass:

static const lua_reg objectLib[] = {
  {"newObject", obj_newobject},
  // etc

void registerObject(PlaydateAPI *playdate) {
  pd = playdate;

  const char *err;

  if (!pd->lua->registerClass("object", objectLib, NULL, 0, &err))
    pd->system->logToConsole("%s:%i: registerClass failed, %s", __FILE__, __LINE__, err);

This has all been working great, but I'm attempting to initialize an LCDSprite in the obj_newobject function, which is now throwing:

static int obj_newobject(lua_State *L) {
  LCDSprite *sprite = pd->sprite->newSprite();
  // rest of init
  return 0;

This code throws with main.lua:<line>: bad argument #1 to 'newObject' (image or tilemap). If i remove the newSprite() call everything is fine.

Let me know if you can see what I'm doing wrong here! Thank you so much.

1 Like

If I pass no arguments to the newObject function it works fine; with 1 or more arguments it does not.

I am facing the same problem.
Perhaps there is a glitch in the Lua customization.

test.lua:44: calling 'setAsTilemap' on bad self (image or tilemap)

When passing self, the error message seems to be a little different, but there appears to be something wrong with the handling of the first argument.

newSpriteTest.zip (4.3 KB)

I have created a simple project to reproduce the phenomenon.
It is confirmed with PlaydateSDK2.0.

The problem in both these cases is pd->sprite->newSprite() gets routed to the Lua sprite creation function but that code is expecting a clean stack, as if it were called from a Lua function. It's a pretty glaring bug, very surprised this hasn't come up before.

I can't think of a good workaround since we don't have direct stack manipulation functions in the C API. :confused: I think the best option until I get this fixed is to create the sprite in Lua and pass it into the C function, retrieve it there with pd->lua->getSprite(1).

I've got this filed, will fix it as soon as I get a chance. Thanks for catching it!


That workaround worked for me! Thanks a bunch :slight_smile:



I'm working on a hybrid system of Lua and C_API and I keep running into this problem.
Please ensure that this is fixed, as each workaround increases the number of detours and may not be practical depending on the number of passes.

Best regards.