diff --git a/lua_embed/bindings.lua b/lua_embed/bindings.lua new file mode 100644 index 0000000..7523aba --- /dev/null +++ b/lua_embed/bindings.lua @@ -0,0 +1,11 @@ +---@meta + +--- Prints a string. +---@param str string The string to print. +function myprint(str) end + +--- Add two integers +---@param a number The first integer +---@param b number The second integer +---@return number Result (a + b) +function c_add(a, b) end diff --git a/lua_embed/main.c b/lua_embed/main.c index aa44ccb..3fa2ad0 100644 --- a/lua_embed/main.c +++ b/lua_embed/main.c @@ -10,9 +10,37 @@ int c_add(lua_State *L) { return 1; // one return value } +int c_print(lua_State *L) { + const char *c = luaL_checkstring(L, 1); + printf("%s\n", c); + return 0; +} + +static int luaB_print(lua_State *L) { + int n = lua_gettop(L); /* number of arguments */ + int i; + for (i = 1; i <= n; i++) { /* for each argument */ + size_t l; + const char *s = luaL_tolstring(L, i, &l); /* convert it to string */ + if (i > 1) /* not the first element? */ + lua_writestring("\t", 1); /* add a tab before it */ + lua_writestring(s, l); /* print it */ + lua_pop(L, 1); /* pop result */ + } + lua_writeline(); + return 0; +} + +static int luaB_type(lua_State *L) { + int t = lua_type(L, 1); + luaL_argcheck(L, t != LUA_TNONE, 1, "value expected"); + lua_pushstring(L, lua_typename(L, t)); + return 1; +} + int main(void) { lua_State *L = luaL_newstate(); - luaL_openlibs(L); // Load Lua standard libraries + // luaL_openlibs(L); // Load Lua standard libraries const lua_Number ver = lua_version(NULL); @@ -21,6 +49,9 @@ int main(void) { // Register the C function as a global Lua function lua_register(L, "c_add", c_add); + lua_register(L, "myprint", c_print); + lua_register(L, "print", luaB_print); + lua_register(L, "type", luaB_type); // Run the Lua script if (luaL_dofile(L, "script.lua") != LUA_OK) { diff --git a/lua_embed/script.lua b/lua_embed/script.lua index 08fb93b..c9f5072 100644 --- a/lua_embed/script.lua +++ b/lua_embed/script.lua @@ -1,8 +1,11 @@ local result = c_add(10, 25) +print("Type: ", type(result)) print("Result from C function: " .. result) HereYouCan = { - "Execute Arbitrary Lua Code" + "Execute Arbitrary Lua Code", } print(HereYouCan[1]) +myprint(HereYouCan[1]) +myprint("Hello" .. " " .. "World")