0
\$\begingroup\$

I am running into a problem in my game engine right now. I want to be able to call Sleep(number_of_seconds) from .lua file (1 only) and halt the execution of the lua file, WHILE the game is running and rendering / updating. When the sleep is done, the .lua file will return execution. Is this possible? All the best, Aldo

p.s. I guess this can be implemented with C++ <thread>but I couldn't find a solution for now:/

\$\endgroup\$
  • \$\begingroup\$ Is sleep a must? You could use an update function and some GetTime function and check if enough time has passed. Or you could use a time-based callback from your engine. I'll elaborate on this if this is a good solution for you. \$\endgroup\$ – akaltar Mar 27 '15 at 19:04
  • \$\begingroup\$ unfortunately my teacher asks me to implement a Sleep AND a Timer function, so I have to do it:p \$\endgroup\$ – Aldo Leka Mar 27 '15 at 21:14
  • \$\begingroup\$ Then your solution is to run the lua script in a separate thread and do synchronizing with mutexes or semaphores.(probably mutexes) \$\endgroup\$ – akaltar Mar 27 '15 at 22:08
  • \$\begingroup\$ Ok thanks I'm going to look into that. Do you have any links of implementation or something to clarify it? \$\endgroup\$ – Aldo Leka Mar 27 '15 at 22:16
1
\$\begingroup\$

Make the lua script a coroutine and have sleep yield

if(now()-timestamp > sleepDuration){ // overflow-proof timeout check
    int oldtop = lua_gettop(L);
    int yielded = lua_resume(L, NULL, 0);
    if(yielded == LUA_YIELD){
        lua_pop(L, lua_gettop(L) - oldtop - 1); //only keep timeout value
        sleepDuration = luaL_checkinteger(L, -1);
        timestamp = now();
        lua_pop(L, 1); //pop timeout
    }
}

You can have sleep() yield multiple values so other wakeup reasons are possible. You can also pass that wakeup reason as a parameter to resume in so the script knows what woke it up.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.