Skip to content

Instantly share code, notes, and snippets.

@E14
Created April 23, 2019 23:35
Show Gist options
  • Save E14/6a258baaa85d4909d12937f3b748a940 to your computer and use it in GitHub Desktop.
Save E14/6a258baaa85d4909d12937f3b748a940 to your computer and use it in GitHub Desktop.
Minimal C-Lua callback
local foo = "INNER";
register(function() print(foo) end);
#include <lua5.3/lua.h>
#include <lua5.3/lauxlib.h>
#include <lua5.3/lualib.h>
static int reg(lua_State *L) {
if(lua_gettop(L)==1 && lua_isfunction(L, -1)) {
// Save callback to "callback" index
lua_setfield(L, LUA_REGISTRYINDEX, "callback");
}
else {/* Handle error */ }
return 0;
}
int main() {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_pushcfunction(L, reg); // |
lua_setglobal(L, "register"); // | Insert api function
luaL_dofile(L, "app.lua");
lua_getfield(L, LUA_REGISTRYINDEX, "callback"); // this would be your
lua_pcall(L, 0, 0, 0); // event callback
return 0;
}
C_FLAGS= -c -Wall -DLUA_USE_APICHECK -std=c99
L_FLAGS= -Wall
L_LIBS= -llua5.3
CC=gcc
LD=gcc
all: main
clean:
rm main.o
main: main.o
$(LD) $(L_FLAGS) -o $@ $< $(L_LIBS)
main.o: main.c
$(CC) $(C_FLAGS) -o $@ $<
install_ubuntu:
sudo apt install liblua5.3-dev
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment