-2

In JNLUA, newThread() is a void function in Java but I don't quite understand the C code behind implementing the java side of the function. Also, would someone explain why the original author would return the index/pointer?

darius sg
  • 11
  • 2

1 Answers1

0

newThread pushes the new thread onto the Lua stack. There is no need to return a value. Interfacing via a pointer value would be challenging to make safe (and poor style anyway I guess), and the index is readily available without returning it (e.g. via getTop or simply by keeping track of the stack size or by using negative indices). This is more or less the same for all parts of the API that push a value onto the stack.

Note that JNLUA's newThread differs a bit from Lua's lua_newthread; threads in JNLUA are a little less general and more intended to be used like Lua coroutines (which are, of course, also Lua threads) -- newThread takes the value from the top of the stack and uses it as the "start function" for the coroutine (which will be invoked when calling resume for the thread the first time).

I won't speculate on the author's decision to expose threads in this way; returning a LuaState (and/or exposing lua_tothread) could also be a reasonable way to implement things a bit closer to the original Lua API.

This is the guts of the implementation:

static int newthread_protected (lua_State *L) {
    lua_State *T;
    
    T = lua_newthread(L);
    lua_insert(L, 1);
    lua_xmove(L, T, 1);
    return 1;
}

This is done in a protected call because lua_newthread can throw an exception (if it runs out of memory). The only argument (and thus the only thing initially on the stack) is the start function at index 1. lua_newthread will push the new thread object to the stack at index 2. Then lua_insert will reverse the order of the new thread object and the start function and lua_xmove transfers the start function to the new thread and then the new thread is returned (which leaves it on top of the caller's stack).

In Lua, a new thread with the start function already on the stack can sort of be treated equivalently to a yielded thread by lua_resume, so this is basically what JNLUA does -- its resume can be used to start the thread with the previously provided function.

tehtmi
  • 676
  • 4
  • 7