calling c++ function from Lua, implement sleep function

You can’t call c function directly from Lua, you have to create a wrapper function that allows calling from Lua. In this post, shows a simple example to implement millisecond sleep function to Lua using nanosleep.

To allow function call from Lua script, your function must obey certain format. As variable passing from Lua to C and vice versa are through Lua Stack, therefore, the wrapper function must pass Lua State as the only parameter.
How about the real function call parameters? We can get it from the stack using lua_tonumber(), lua_tostring() etc. To return result of function call, we use lua_pushnumber(), lua_pushstring() etc. Because Lua function allows return more than 1 results, therefore you need tell Lua by returning an integer value.

    static int Function_Name (lua_State *L) {
      int i = lua_tointeger(L, 1);  /* get argument */
      /* carry on the procedures here ... */
      lua_pushinteger(L, sin(d));  /* push result */
      return 1;  /* number of results */

We need to setup a library to contain your functions. By doing this, construct a static structure in array. Next, we load up our lib by calling luaL_openlib() and at last, to trigger a dofile().

Lets check out the sample codes on how to implement msleep function to Lua.

extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"


int L_MSleep(lua_State* l)
    int milisec=0;
    struct timespec req={0};
    time_t sec;

    milisec=luaL_optint(l,1,0); // obtain parameter

    if (milisec==0)
       return 0;




    return 1;

int main()

    const static struct luaL_reg misc [] = {  
        {"msleep", &L_MSleep},
        {NULL,NULL} //must!

    lua_State *L = lua_open();
    //open your lib
    luaL_openlib(L, "misc", misc, 0);

    if (luaL_loadfile(L, "callc.lua") || lua_pcall(L, 0, 0, 0))
        printf("error: %s", lua_tostring(L, -1));

    return 0;

From the example above, we implemented msleep() that takes only 1 parameter, and we created a library “misc” in Lua. luaL_optint() is actually a clean version of doing lua_isinteger() and lua_tointeger(). luaL_optint() takes 3 parameter,

 luaL_optint(Lua State, Stack Number, Default Value)

If the param specified by lua function call is not integer, the default value will be assigned.

So let see how we can call that from Lua script.

for i=1,9,1 do
    io.write(string.format("[%d] Hello\n",i))
    misc.msleep(1000) -- sleep 1 sec

Check out for more details from Programming in Lua Chapter 26 [1].

And more Lua examples here,

[1] Programming In Lua, Chapter 26 #Calling C from Lua

One thought on “calling c++ function from Lua, implement sleep function

  1. Pingback: Recent Links Tagged With "usleep" - JabberTags

Leave a Reply

Your email address will not be published. Required fields are marked *