From c83e5d2713334d39bf0718f626cab387f7331a98 Mon Sep 17 00:00:00 2001 From: Mitja Felicijan Date: Thu, 17 Jul 2025 17:13:45 +0200 Subject: Added exposed C functions to Lua embed --- c-embed-lua/hi.h | 13 +++++++++++-- c-embed-lua/hi.lua | 7 +++++++ c-embed-lua/main.c | 11 +++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) (limited to 'c-embed-lua') diff --git a/c-embed-lua/hi.h b/c-embed-lua/hi.h index c339ac6..630da70 100644 --- a/c-embed-lua/hi.h +++ b/c-embed-lua/hi.h @@ -169,6 +169,15 @@ unsigned char hi[] = { 0x28, 0x29, 0x20, 0x64, 0x6f, 0x0a, 0x09, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x28, 0x6c, 0x69, 0x6e, 0x65, 0x29, 0x0a, 0x65, 0x6e, 0x64, 0x0a, 0x0a, 0x66, 0x69, 0x6c, 0x65, 0x3a, 0x63, 0x6c, 0x6f, 0x73, 0x65, 0x28, 0x29, - 0x0a + 0x0a, 0x0a, 0x2d, 0x2d, 0x20, 0x45, 0x78, 0x70, 0x6f, 0x73, 0x69, 0x6e, + 0x67, 0x20, 0x43, 0x20, 0x66, 0x75, 0x6e, 0x63, 0x74, 0x69, 0x6f, 0x6e, + 0x73, 0x2e, 0x0a, 0x0a, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x28, 0x22, + 0x45, 0x78, 0x70, 0x6f, 0x73, 0x69, 0x6e, 0x67, 0x20, 0x43, 0x20, 0x66, + 0x75, 0x6e, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x29, 0x0a, 0x0a, + 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x20, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, + 0x20, 0x3d, 0x20, 0x63, 0x5f, 0x73, 0x75, 0x6d, 0x28, 0x33, 0x2c, 0x20, + 0x35, 0x29, 0x0a, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x28, 0x22, 0x53, 0x75, + 0x6d, 0x20, 0x69, 0x73, 0x22, 0x2c, 0x20, 0x72, 0x65, 0x73, 0x75, 0x6c, + 0x74, 0x29, 0x0a }; -unsigned int hi_len = 2041; +unsigned int hi_len = 2151; diff --git a/c-embed-lua/hi.lua b/c-embed-lua/hi.lua index fb6621c..1f2c072 100644 --- a/c-embed-lua/hi.lua +++ b/c-embed-lua/hi.lua @@ -104,3 +104,10 @@ for line in file:lines() do end file:close() + +-- Exposing C functions. + +header("Exposing C functions") + +local result = c_sum(3, 5) +print("Sum is", result) diff --git a/c-embed-lua/main.c b/c-embed-lua/main.c index 7ab678a..662ea70 100644 --- a/c-embed-lua/main.c +++ b/c-embed-lua/main.c @@ -4,10 +4,21 @@ #include "hi.h" +static int l_sum(lua_State *L) { + double a = luaL_checknumber(L, 1); + double b = luaL_checknumber(L, 2); + lua_pushnumber(L, a + b); + return 1; +} + int main(void) { lua_State *L = luaL_newstate(); luaL_openlibs(L); + // You do not need to prefix name of the function with `c_`. I did it to + // make it clear in the lua script code that this is a custom function. + lua_register(L, "c_sum", l_sum); + // Not wise since this is not a null-terminated string. /* luaL_dostring(L, (const char*)hi); */ -- cgit v1.2.3