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.

Continue reading

Accessing Lua global variables from c++

Calling Lua scripts from c++’s example was written in post How to embed Lua 5.1 in C++. Now, let us look at how to access Lua’s global variables from c++.

Value passing between c++ and Lua rely on Lua stack. Stack is a data structure based on the principle of Last In First Out (LIFO). This is very important keep in mind while coding with C API of Lua.

P.S: I am using Lua 5.1.3′s C API.

Continue reading

GNU readline: Implement Custom Auto-complete

GNU readline implement filename auto-complete by default, it will list all the files in the current directory. We can disable it by binds our TAB key to some other operation. In previous post, I simply abort the operation to ignore users hitting TABs.

Auto-complete are useful if only we can customize it. Well, readline allows us do it by assign our own callback functions. First of all, you may want to read up the manual from HERE. It does provides a c sample codes as well but I find it too complicated, here I provide a simplified version that can be compiled under c++.

Continue reading