1---
 2title: Extend Lua with custom C functions using Clang
 3url: extend-lua-with-custom-c.html
 4date: 2023-05-23T12:00:00+02:00
 5type: note
 6draft: false
 7tags: [c]
 8---
 9
10Here is a boilerplate for extending Lua with custom C functions. This requires
11Clang and Lua 5.1 to be installed. GCC can be used instead of Clang, but the
12Makefile will need to be modified.
13
14- nativefunc.c
15
16  ```c
17  #include <lua.h>
18  #include <lauxlib.h>
19
20  static int l_mult50(lua_State *L) {
21    double number = luaL_checknumber(L, 1);
22    lua_pushnumber(L, number * 50);
23    return 1;
24  }
25
26  int luaopen_nativefunc(lua_State *L) {
27    static const struct luaL_Reg nativeFuncLib[] = { {"mult50", l_mult50}, {NULL, NULL} };
28
29    luaL_register(L, "nativelib", nativeFuncLib);
30    return 1;
31  }
32  ```
33
34- main.lua
35
36  ```lua
37  require "nativefunc"
38  print(nativelib.mult50(50))
39  ```
40
41- Makefile
42
43  ```Makefile
44  CC       = clang
45  CFLAGS   =
46  INCLUDES = `pkg-config lua5.1 --cflags-only-I`
47
48  all:
49    $(CC) -shared -o nativefunc.so -fPIC nativefunc.c $(CFLAGS) $(INCLUDES)
50
51  clean:
52    rm *.so
53  ```
54