diff options
| author | Mitja Felicijan <mitja.felicijan@gmail.com> | 2023-05-24 08:43:08 +0200 |
|---|---|---|
| committer | Mitja Felicijan <mitja.felicijan@gmail.com> | 2023-05-24 08:43:08 +0200 |
| commit | da066db1d2cb9496528c5a6b064b9bea17570ba9 (patch) | |
| tree | e9a0e4a4d28398632ed4a866fa71d20bc930f7b0 /content/notes/extend-lua-with-custom-c.md | |
| parent | dcf5ee0982f7dbf22a8dcb05063976299216d246 (diff) | |
| download | mitjafelicijan.com-da066db1d2cb9496528c5a6b064b9bea17570ba9.tar.gz | |
Note: Extending Lua with C
Diffstat (limited to 'content/notes/extend-lua-with-custom-c.md')
| -rw-r--r-- | content/notes/extend-lua-with-custom-c.md | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/content/notes/extend-lua-with-custom-c.md b/content/notes/extend-lua-with-custom-c.md new file mode 100644 index 0000000..ba0a046 --- /dev/null +++ b/content/notes/extend-lua-with-custom-c.md | |||
| @@ -0,0 +1,53 @@ | |||
| 1 | --- | ||
| 2 | title: Extend Lua with custom C functions using Clang | ||
| 3 | url: extend-lua-with-custom-c.html | ||
| 4 | date: 2023-05-24 | ||
| 5 | type: notes | ||
| 6 | draft: false | ||
| 7 | tags: [lua, clang, c] | ||
| 8 | --- | ||
| 9 | |||
| 10 | Here is a boilerplate for extending Lua with custom C functions. This requires | ||
| 11 | Clang and Lua 5.1 to be installed. GCC can be used instead of Clang, but the | ||
| 12 | Makefile 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 | ``` | ||
