Last active
January 10, 2019 23:11
-
-
Save d-lua-stuff/f1564985746f1ec38de200cfa2f6a59b to your computer and use it in GitHub Desktop.
Lua console with debug.traceback() available as a global
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 <assert.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <lua.h> | |
#include <lauxlib.h> | |
#include <lualib.h> | |
// from https://www.lua.org/pil/24.2.3.html | |
static void stackDump(lua_State *L) { | |
int i; | |
int top = lua_gettop(L); | |
for (i = 1; i <= top; i++) { /* repeat for each level */ | |
int t = lua_type(L, i); | |
switch (t) { | |
case LUA_TSTRING: /* strings */ | |
printf("`%s'", lua_tostring(L, i)); | |
break; | |
case LUA_TBOOLEAN: /* booleans */ | |
printf(lua_toboolean(L, i) ? "true" : "false"); | |
break; | |
case LUA_TNUMBER: /* numbers */ | |
printf("%g", lua_tonumber(L, i)); | |
break; | |
default: /* other values */ | |
printf("%s", lua_typename(L, t)); | |
break; | |
} | |
printf(" "); /* put a separator */ | |
} | |
printf("\r\n"); /* end the listing */ | |
} | |
// modified interactive Lua console from https://www.lua.org/pil/24.1.html | |
int main() | |
{ | |
char buff[256]; | |
int error; | |
int ret; | |
lua_State *L = luaL_newstate(); | |
// Load some of the standard library | |
luaL_requiref(L, "_G", luaopen_base, 1); | |
luaL_requiref(L, "math", luaopen_math, 1); | |
luaL_requiref(L, "package", luaopen_package, 1); | |
luaL_requiref(L, "table", luaopen_table, 1); | |
luaL_requiref(L, "string", luaopen_string, 1); | |
lua_pop(L, 5); // luaL_requiref leaves a copy of the module table on the stack; pop those tables | |
// Store the debug.traceback() function as a global, without the rest of the debug library available | |
luaopen_debug(L); // stack now contains: debug table | |
stackDump(L); | |
ret = lua_getfield(L, -1, "traceback"); // stack now contains: debug table, traceback fn | |
assert(LUA_TFUNCTION == ret); | |
stackDump(L); | |
lua_setglobal(L, "traceback"); // stack now contains: debug table | |
stackDump(L); | |
lua_pop(L, 1); // stack is now empty | |
while (printf("> ") && fgets(buff, sizeof(buff), stdin)) | |
{ | |
error = luaL_loadbuffer(L, buff, strlen(buff), "line") || lua_pcall(L, 0, 0, 0); | |
if (error) | |
{ | |
fprintf(stderr, "%s\n", lua_tostring(L, -1)); | |
lua_pop(L, 1); /* pop error message from the stack */ | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment