1#include "lua-5.4.8/src/lua.h"
2#include "lua-5.4.8/src/lualib.h"
3#include "lua-5.4.8/src/lauxlib.h"
4
5#include "hi.h"
6
7static int l_sum(lua_State *L) {
8 double a = luaL_checknumber(L, 1);
9 double b = luaL_checknumber(L, 2);
10 lua_pushnumber(L, a + b);
11 return 1;
12}
13
14int main(void) {
15 lua_State *L = luaL_newstate();
16 luaL_openlibs(L);
17
18 // You do not need to prefix name of the function with `c_`. I did it to
19 // make it clear in the lua script code that this is a custom function.
20 lua_register(L, "c_sum", l_sum);
21
22 // Not wise since this is not a null-terminated string.
23 /* luaL_dostring(L, (const char*)hi); */
24
25 // https://www.lua.org/manual/5.4/manual.html#luaL_loadbuffer
26 // Load Lua chunk from `hi` buffer.
27 if (luaL_loadbuffer(L, (const char*)hi, hi_len, "hi_chunk") != LUA_OK) {
28 fprintf(stderr, "Load error: %s\n", lua_tostring(L, -1));
29 lua_pop(L, 1);
30 } else {
31 // Execute the chunk.
32 if (lua_pcall(L, 0, 0, 0) != LUA_OK) {
33 fprintf(stderr, "Runtime error: %s\n", lua_tostring(L, -1));
34 lua_pop(L, 1);
35 }
36 }
37
38 lua_close(L);
39 return 0;
40}