aboutsummaryrefslogtreecommitdiff
path: root/content/notes/2023-05-23-extend-lua-with-custom-c.md
diff options
context:
space:
mode:
authorMitja Felicijan <mitja.felicijan@gmail.com>2024-03-10 14:59:14 +0100
committerMitja Felicijan <mitja.felicijan@gmail.com>2024-03-10 14:59:14 +0100
commit1100562e29f6476448b656dbddd4cf22505523f6 (patch)
tree442eec492199104bd49dfd74474ce89ade8fcac9 /content/notes/2023-05-23-extend-lua-with-custom-c.md
parenta40d80be378e46a6c490e1b99b0d8f4acd968503 (diff)
downloadmitjafelicijan.com-1100562e29f6476448b656dbddd4cf22505523f6.tar.gz
Move back to JBMAFP
Diffstat (limited to 'content/notes/2023-05-23-extend-lua-with-custom-c.md')
-rw-r--r--content/notes/2023-05-23-extend-lua-with-custom-c.md53
1 files changed, 53 insertions, 0 deletions
diff --git a/content/notes/2023-05-23-extend-lua-with-custom-c.md b/content/notes/2023-05-23-extend-lua-with-custom-c.md
new file mode 100644
index 0000000..013616b
--- /dev/null
+++ b/content/notes/2023-05-23-extend-lua-with-custom-c.md
@@ -0,0 +1,53 @@
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
7---
8
9Here is a boilerplate for extending Lua with custom C functions. This requires
10Clang and Lua 5.1 to be installed. GCC can be used instead of Clang, but the
11Makefile will need to be modified.
12
13- nativefunc.c
14
15 ```c
16 #include <lua.h>
17 #include <lauxlib.h>
18
19 static int l_mult50(lua_State *L) {
20 double number = luaL_checknumber(L, 1);
21 lua_pushnumber(L, number * 50);
22 return 1;
23 }
24
25 int luaopen_nativefunc(lua_State *L) {
26 static const struct luaL_Reg nativeFuncLib[] = { {"mult50", l_mult50}, {NULL, NULL} };
27
28 luaL_register(L, "nativelib", nativeFuncLib);
29 return 1;
30 }
31 ```
32
33- main.lua
34
35 ```lua
36 require "nativefunc"
37 print(nativelib.mult50(50))
38 ```
39
40- Makefile
41
42 ```Makefile
43 CC = clang
44 CFLAGS =
45 INCLUDES = `pkg-config lua5.1 --cflags-only-I`
46
47 all:
48 $(CC) -shared -o nativefunc.so -fPIC nativefunc.c $(CFLAGS) $(INCLUDES)
49
50 clean:
51 rm *.so
52 ```
53