lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello,

I am trying to create a new lua_state for setting it in a callback used from
another thread.
First i use setCallback which creates the state and compiles the chunk.
afterwards i use RtAudio::openStream and set cbMix as the callback
line *buffer++ = luaL_checknumber(L, -1);
is making it to crash.

Is there something i am doing wrong?

static lua_State *callback_state=0;
int setCallback(lua_State *L){
   const char *chunk = luaL_checkstring(L, 1);
   lua_State *L1 = luaL_newstate();
   if (L1 == NULL)
       luaL_error(L, "unable to create new state");
   if (luaL_loadstring(L1, chunk) != 0)
       luaL_error(L, "error starting thread: %s",lua_tostring(L1, -1));
   luaL_openlibs(L1); /* open standard libraries */
   if (lua_pcall(L1, 0, 0, 0) != 0) /* call main chunk */
       fprintf(stderr, "thread error: %s", lua_tostring(L1, -1));
   lua_gc(L1, LUA_GCSTOP,0);
   callback_state = L1;
   return 0;
}

static int cbMix(void *outputBuffer, void *inputBuffer, unsigned int
nFrames, double streamTime, RtAudioStreamStatus status, void *data){
   if (callback_state!=0){
       lua_State *L = callback_state;
       lua_gc(L, LUA_GCSTOP,0);
       lua_getglobal(L, "thecallback"); /* function to be called */
       lua_pushnumber(L, nFrames); /* push 1st argument */
       if (lua_pcall(L, 1, 1, 0) != 0)
           printf("error running function 'thecallback':
%s",lua_tostring(L, -1));
       if(!lua_istable(L,-1))
           printf("error running function 'thecallback': did not returned
table");
       double *buffer = (double *) outputBuffer;
       for (int i=0; i<nFrames; i++ ) {
           for (int j=0; j<2; j++ ) {
               lua_rawgeti(L, -1,i*2+j+1);
               *buffer++ = luaL_checknumber(L, -1);
           }
       }
       lua_pop(L, 1); /* pop returned value */
   }
   return 0;
}

best
victor bombi