Skip to content

Instantly share code, notes, and snippets.

@prozacgod
Created April 24, 2020 01:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prozacgod/cd51dc767ea0925b3f7b45e990f4b883 to your computer and use it in GitHub Desktop.
Save prozacgod/cd51dc767ea0925b3f7b45e990f4b883 to your computer and use it in GitHub Desktop.
Calling a callback sent from lua to c
// taken from here https://stackoverflow.com/a/21947358 and made into single file
// I was using luajit like this from my own game's code gcc example.c -L ./luajit/LuaJIT-2.0.5/src/ -lluajit
#include <stdio.h>
#include <stdlib.h>
#include "./luajit/LuaJIT-2.0.5/src/lua.h"
#include "./luajit/LuaJIT-2.0.5/src/lauxlib.h"
#include "./luajit/LuaJIT-2.0.5/src/lualib.h"
int callback_reference = 0;
int lua_registerCallback( lua_State *L ) {
callback_reference = luaL_ref( L, LUA_REGISTRYINDEX );
return 0;
}
void call_callback( lua_State *L ) {
lua_rawgeti( L, LUA_REGISTRYINDEX, callback_reference );
lua_pushvalue( L, 1 );
if ( 0 != lua_pcall( L, 0, 0, 0 ) ) {
printf("Failed to call the callback!\n %s\n", lua_tostring( L, -1 ) );
return;
}
callback_reference = luaL_ref( L, LUA_REGISTRYINDEX );
}
char* luaCode =
"function MyCallback()\n"
" print(\"Hello World!\")\n"
"end\n"
"RegisterCallback( MyCallback )\n";
int main( void ) {
lua_State *L = lua_open();
luaL_openlibs( L );
lua_pushcfunction( L, lua_registerCallback );
lua_setglobal( L, "RegisterCallback" );
if ( 0 != luaL_dostring( L, luaCode ) ) {
printf("Failed to load calback.lua!\n %s",
lua_tostring( L, -1 ) );
lua_close( L );
return 1;
}
call_callback( L );
call_callback( L );
luaL_unref( L, LUA_REGISTRYINDEX, callback_reference );
lua_close( L );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment