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