Last active
May 19, 2020 14:54
-
-
Save wojas/f16bb9d1f9d7bfbc97b33a1db1baf4ff to your computer and use it in GitHub Desktop.
Quick and dirty example of how to wrap a callback registration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cmake_minimum_required(VERSION 3.16) | |
project(luac C) | |
set(CMAKE_C_STANDARD 11) | |
find_package(PkgConfig REQUIRED) | |
pkg_search_module(LUA REQUIRED IMPORTED_TARGET luajit luajit2) | |
add_executable(retval retval.c) | |
target_link_libraries(retval PUBLIC PkgConfig::LUA) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <lua.h> | |
#include <lauxlib.h> | |
#include <lualib.h> | |
// This is the code registered by the user as a string | |
char usercode[] = "return function() return 42 end"; | |
char header[] = "callback = (function()\n"; | |
char footer[] = "\nend)()"; | |
char buf[1024] = ""; | |
// Call wrapper we use to avoid checking the retval with LuaWrappers. | |
int main (void) { | |
strcat(buf, header); | |
strcat(buf, usercode); | |
strcat(buf, footer); | |
int error; | |
lua_State *L = lua_open(); /* opens Lua */ | |
luaL_openlibs(L); | |
error = luaL_loadbuffer(L, buf, strlen(buf), "line") || lua_pcall(L, 0, 0, 0); | |
if (error) { | |
fprintf(stderr, "%s", lua_tostring(L, -1)); | |
lua_pop(L, 1); /* pop error message from the stack */ | |
return 1; | |
} | |
lua_getglobal(L, "callback"); | |
if (lua_pcall(L, 0, 1, 0) != 0) { | |
fprintf(stderr, "%s", lua_tostring(L, -1)); | |
return 1; | |
} | |
if (!lua_isnumber(L, -1)) { | |
fprintf(stderr, "not a number\n"); | |
return 1; | |
} | |
int n = lua_tonumber(L, -1); | |
lua_pop(L, 1); | |
fprintf(stderr, "res: %i\n", n); // prints 42 | |
lua_close(L); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment