From c40c698ece5767a3cbf0c965ce9388489ce49e20 Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Mon, 18 Aug 2025 11:23:04 +0200 Subject: [PATCH] Lua loadable c library example (.so) --- lua_lib/Makefile | 21 +++++++++++++++++++++ lua_lib/driver.lua | 2 ++ lua_lib/lua_lookup3.c | 27 +++++++++++++++++++++++++++ 3 files changed, 50 insertions(+) create mode 100644 lua_lib/Makefile create mode 100644 lua_lib/driver.lua create mode 100644 lua_lib/lua_lookup3.c diff --git a/lua_lib/Makefile b/lua_lib/Makefile new file mode 100644 index 0000000..001e6e9 --- /dev/null +++ b/lua_lib/Makefile @@ -0,0 +1,21 @@ +CC ?= gcc +CFLAGS ?= -Wall -O2 -fPIC +LDFLAGS ?= + +TARGET = lookup3.so +SRC = lua_lookup3.c +OBJS = lua_lookup3.o lookup3.o + +all: $(TARGET) + +$(TARGET): $(OBJS) + $(CC) -shared -o $@ $^ $(LDFLAGS) + +lua_lookup3.o: $(SRC) + $(CC) $(CFLAGS) -c -o $@ $< + +lookup3.o: ../lookup3.c + $(CC) $(CFLAGS) -c -o $@ $< + +clean: + rm -f $(TARGET) $(OBJS) diff --git a/lua_lib/driver.lua b/lua_lib/driver.lua new file mode 100644 index 0000000..84dd76b --- /dev/null +++ b/lua_lib/driver.lua @@ -0,0 +1,2 @@ +local myhash = require "lookup3" +print(myhash.lookup3("hello", 0) % 100) diff --git a/lua_lib/lua_lookup3.c b/lua_lib/lua_lookup3.c new file mode 100644 index 0000000..eaa11cc --- /dev/null +++ b/lua_lib/lua_lookup3.c @@ -0,0 +1,27 @@ +#include +#include +#include + +uint32_t lookup3(const void *key, size_t length, uint32_t initval); + +// Lua wrapper +static int l_lookup3(lua_State *L) { + size_t len; + const char *str = luaL_checklstring(L, 1, &len); // get string + length + uint32_t initval = (uint32_t)luaL_checkinteger(L, 2); // get initval + + uint32_t hash = lookup3(str, len, initval); + + lua_pushinteger(L, hash); // return the hash + return 1; // number of return values +} + +// Module open function +int luaopen_lookup3(lua_State *L) { + lua_newtable(L); + + lua_pushcfunction(L, l_lookup3); + lua_setfield(L, -2, "lookup3"); + + return 1; // return the table +}