Bodies sometimes don't get created?

I noticed that sometimes World.addBody will return null instead of the body if I add a bunch of them in a row.

Quote:
body = addBody(bd);
shape = body.createShape(sd);


Sometimes I will get a NullPointerException on the second line. This is a problem, since my game includes Lua scripting.

Any way to fix this?

EDIT: Looking at the code, I figured out that this happens when you try to add a body while it is stepping the simulation (this was happening since the Lua scripting and physics ran on different threads). I'll see if I can figure out a way to make it wait until the step is over to add the body.
I ran in to this problem with the C++ version. There I could solve it by running my add function on the same thread that does the stepping, thus effectively queuing it until the current step returns.

As for waiting until a step is complete outside of the thread, I think you should be able to check wheter the world is currently stepping by determining wheter it is locked or not by using b2World::IsLocked(). If it return false, it should be safe to add a body.
Maybe you can simply use synchronize:
Code:
synchronize(external){
  world.step(...);
}

and in your threads
Code:
synchronize(external){
  body = addBody(bd);
  shape = body.createShape(sd);
}

obviously external must point at the same variable/class for the threads, i think you can use the thread that contains world.step() as parameter of synchronize() 😁
hope it will help you

Original thread: https://box2d.org/forum/viewtopic.php?t=4417