C language extension to implement the Lua sleep function

  • 2020-04-02 03:03:31
  • OfStack

In these days to do a small project, which USES some of the basic apis, such as sleep, access to the current directory, and so on, the lua in the standard library does not provide these interfaces, although the third-party libraries also have achieved, but with a few functions, in an embedded system installed so many third-party libraries is a little waste of resources, so the @ victory brother wrote a C implementation of socket, and then use to me. I'm going to try to implement some of the other functions in C, so let's first see how we can write an extension of lua in C.

Part C

First, according to the Lua C language protocol to write the call module, compiled into. So file, and then can be called in the Lua script. Below is a sleep implementation written in Ubuntu14.04 ** based on lua5.1**.


*sleep.c file *
/* Learn to write lua c By extension, it provides itself for some simple functions C expand
 *ubuntu compile $ gcc -fPIC -shared -llua sleep.c -o orangleliu.so -I/usr/include/lua5.1 -std=gnu99
 */ #include "unistd.h"
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

static int sleep_c (lua_State *L){
    long secs = lua_tointeger(L, -1);
    sleep(secs);
    return 0;                        
} static const struct luaL_Reg libs[] = {
    {"sleep", sleep_c},
    {NULL, NULL} 
}; int luaopen_orangleliu (lua_State *L){
   
    luaL_register(L, "orangleliu", libs);
    return 1;
}

compile


$ gcc -fPIC -shared -llua sleep.c -o orangleliu.so -I/usr/include/lua5.1 -std=gnu99

Lua calls

test.lua
require "orangleliu"
print(os.time())
orangleliu.sleep(1)
print(os.time())

The results


$ lua test.lua
1427118862
1427118863

summary

This is what a basic template looks like. More complex is multiple parameters and multiple return values. If you have a C base, it's pretty fast to write, but it's pretty cumbersome to work with across platforms. You can search the lua extension library written by others on github for reference.


Related articles: