tags:

views:

3134

answers:

6

I cant figure out how to get lua to do any common timing tricks, such as

  • sleep - stop all action on thread

  • pause/wait - don't go on to the next command, but allow other code in the application to continue

  • block - don't go on to next command until the current one returns

And I've read that a

while os.clock()<time_point do 
--nothing
end

eats up CPU time.

Any suggestions? Is there an API call I'm missing?

+1  A: 

You want  win.Sleep(milliseconds), methinks.

Yeah, you definitely don't want to do a busy-wait like you describe.

chaos
+1  A: 

I would implement a simple function to wrap the host system's sleep function in C.

John Cromartie
+2  A: 

I agree with John on wrapping the sleep function. You could also use this wrapped sleep function to implement a pause function in lua (which would simply sleep then check to see if a certain condition has changed every so often). An alternative is to use hooks.

I'm not exactly sure what you mean with your third bulletpoint (don't commands usually complete before the next is executed?) but hooks may be able to help with this also.

See: Question: How can I end a Lua thread cleanly? for an example of using hooks.

CiscoIPPhone
+1  A: 

Pure Lua uses only what is in ANSI standard C. Luiz Figuereido's lposix module contains much of what you need to do more systemsy things.

Norman Ramsey
+1  A: 

You can't do it in pure Lua without eating CPU, but there's a simple, non-portable way:

os.execute("sleep 1")

(it will block)

Kknd
+1  A: 

[I was going to post this as a comment on John Cromartie's post, but didn't realize you couldn't use formatting in a comment.]

I agree. Dropping it to a shell with os.execute() will definitely work but in general making shell calls is expensive. Wrapping some C code will be much quicker at run-time. In C/C++ on a Linux system, you could use:

static int lua_sleep(lua_State *L)
{
    int m = static_cast<int> (luaL_checknumber(L,1));
    usleep(m * 1000); 
    // usleep takes nanoseconds. This converts the parameter to milliseconds. 
    // Change this as necessary. 
    // Alternatively, use 'sleep()' to treat the parameter as whole seconds. 
    return 0;
}

Then, in main, do:

lua_pushcfunction(L, lua_sleep);
lua_setglobal(L, "sleep");

where "L" is your lua_State. Then, in your Lua script called from C/C++, you can use your function by calling:

sleep(1000) -- Sleeps for one second
Zack