Skip to content

Instantly share code, notes, and snippets.

@jarcode-foss
Created July 10, 2022 15:13
Show Gist options
  • Save jarcode-foss/09ba1ffbccfdd44450e3232a9d82aea7 to your computer and use it in GitHub Desktop.
Save jarcode-foss/09ba1ffbccfdd44450e3232a9d82aea7 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
#include "luajit-2.1/luajit.h"
#include "luajit-2.1/luaconf.h"
#include "luajit-2.1/lua.h"
#include "luajit-2.1/lauxlib.h"
#include "luajit-2.1/lualib.h"
#define ENDL "\n"
static char* lua_source =
"if type(jit) ~= \"table\" then print(\"not running under luajit\") end" ENDL
"local function lua_function_that_yields()" ENDL
" print(\"calling coroutine.yield()...\")" ENDL
" coroutine.yield()" ENDL
"end" ENDL
"local c1 = coroutine.create(function() " ENDL
" print(\"start\")" ENDL
" fcall(lua_function_that_yields)" ENDL
" print(\"end\")" ENDL
"end)" ENDL
"while coroutine.status(c1) ~= \"dead\" do" ENDL
" print(\"resuming...\")" ENDL
" local ok, err = coroutine.resume(c1)" ENDL
" if not ok then" ENDL
" error(\"coroutine failed: \" .. err)" ENDL
" end" ENDL
"end" ENDL;
static int lua_fcall(lua_State* L) {
if (lua_type(L, 1) != LUA_TFUNCTION) {
fprintf(stderr, "not a function\n");
abort();
} else {
printf("`lua_fcall` invoked with lua function\n");
}
lua_call(L, 0, 0);
}
bool calltop(lua_State* L) {
switch (lua_pcall(L, 0, 0, 0)) {
case 0: break;
case LUA_ERRRUN:
case LUA_ERRMEM:
default: {
const char* ret = lua_tostring(L, -1);
fprintf(stderr, "unexpected error running chunk: %s\n", ret);
return false;
}
case LUA_ERRERR: {
fprintf(stderr, "error running non-existent error handler function (?)\n");
return false;
}
}
return true;
}
int main(int argc, char** argv) {
lua_State* L = luaL_newstate();
luaL_openlibs(L);
lua_pushcfunction(L, lua_fcall);
lua_setglobal(L, "fcall");
luaL_loadstring(L, lua_source);
assert(calltop(L) == false);
}
// linux: gcc luajit_exception_test.c -fexceptions -lluajit-5.1 -o luajit_exception_test
// windows: x86_64-w64-mingw32-gcc luajit_exception_test.c -fexceptions -lluajit-2.1.a -o luajit_exception_test.exe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment