1. 程式人生 > >c or lua sleep ms

c or lua sleep ms

// sleepms.c // 編譯命令: gcc -g -O2 -Wall -fPIC --shared sleepms.c -o sleepms.so
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <math.h>
#include <sys/select.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

static int sleep_ms(lua_State *L) {
    int secs = luaL_checknumber(L, 1);
    struct timeval tval;
    tval.tv_sec=secs/1000;
    tval.tv_usec=(secs*1000)%1000000;
    select(0,NULL,NULL,NULL,&tval);
    return 1;
}

static const struct luaL_Reg l[] = {
    {"sleep_ms", sleep_ms},
    { NULL, NULL}
};

int luaopen_sleepms(lua_State *L) {
  luaL_newlib(L, l);
  return 1;
}

//測試用例:
local sleepms = require "sleepms"

print(os.time())
sleepms.sleep_ms(2000)
print(os.time())