aboutsummaryrefslogtreecommitdiff
path: root/content/notes/2023-05-23-extend-lua-with-custom-c.md
diff options
context:
space:
mode:
authorMitja Felicijan <m@mitjafelicijan.com>2023-07-16 22:46:06 +0200
committerMitja Felicijan <m@mitjafelicijan.com>2023-07-16 22:46:11 +0200
commit0cb6a5c81271a61e930505f3315b1d67bdf22724 (patch)
tree27df39e2004dda656f5e8ae09e9d4e6395d4f903 /content/notes/2023-05-23-extend-lua-with-custom-c.md
parent89b2019bfa3bd8f1f0ceb7724c492fdf337dd519 (diff)
downloadmitjafelicijan.com-0cb6a5c81271a61e930505f3315b1d67bdf22724.tar.gz
Renamed all the notes files to include date
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.md54
1 files changed, 54 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..554a6a4
--- /dev/null
+++ b/content/notes/2023-05-23-extend-lua-with-custom-c.md
@@ -0,0 +1,54 @@
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: [lua, 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