diff options
| author | Mitja Felicijan <m@mitjafelicijan.com> | 2023-07-12 18:35:08 +0200 |
|---|---|---|
| committer | Mitja Felicijan <m@mitjafelicijan.com> | 2023-07-12 18:35:08 +0200 |
| commit | 23a56bd50b04211da3cab45f72c3390711b2416b (patch) | |
| tree | ab9a4a0136b4cce06dba7d853e296f682f807dbb /content/notes/extend-lua-with-custom-c.md | |
| parent | cecb4b48a39a3558979b9c4b50e45bf605a3684e (diff) | |
| download | mitjafelicijan.com-23a56bd50b04211da3cab45f72c3390711b2416b.tar.gz | |
Moved notes and posts into subfolders
Diffstat (limited to 'content/notes/extend-lua-with-custom-c.md')
| -rw-r--r-- | content/notes/extend-lua-with-custom-c.md | 54 |
1 files changed, 54 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..554a6a4 --- /dev/null +++ b/content/notes/extend-lua-with-custom-c.md | |||
| @@ -0,0 +1,54 @@ | |||
| 1 | --- | ||
| 2 | title: Extend Lua with custom C functions using Clang | ||
| 3 | url: extend-lua-with-custom-c.html | ||
| 4 | date: 2023-05-23T12:00:00+02:00 | ||
| 5 | type: note | ||
| 6 | draft: false | ||
| 7 | tags: [lua, 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 | ``` | ||
| 54 | |||
