Minor improvements to LuaConsole.cpp

This commit is contained in:
2021-01-23 20:12:21 -05:00
parent 37a05fe1ac
commit df3ec8ab99
3 changed files with 61 additions and 57 deletions

View File

@@ -42,18 +42,6 @@ static void l_message(const char *msg)
fflush(stderr);
}
static int report(lua_State *L, int status)
{
if (status && !lua_isnil(L, -1))
{
const char *msg = lua_tostring(L, -1);
if (msg == NULL)
msg = "(error object is not a string)";
l_message(msg);
lua_pop(L, 1);
}
return status;
}
static void doexp(lua_State *L, const std::string &exp)
{
@@ -63,23 +51,29 @@ static void doexp(lua_State *L, const std::string &exp)
signal(SIGINT, laction);
status = traceback_pcall(L, 0, LUA_MULTRET);
signal(SIGINT, SIG_DFL);
if (status != LUA_OK) {
report(L, status);
if (status == LUA_OK) {
if (lua_gettop(L) > 0) {
lua_getglobal(L, "pprint");
if (lua_isnil(L, -1)) {
lua_pop(L, 1);
lua_getglobal(L, "print");
}
lua_insert(L, 1);
if (lua_pcall(L, lua_gettop(L) - 1, 0, 0) != 0) {
l_message(
lua_pushfstring(L, "error calling 'print' (%s)",
lua_tostring(L, -1)));
}
}
} else {
const char *msg = lua_tostring(L, -1);
if (msg == NULL) {
msg = "(error object is not a string)";
}
l_message(msg);
lua_pop(L, 1);
lua_gc(L, LUA_GCCOLLECT, 0);
}
if (status == LUA_OK && lua_gettop(L) > 0) {
lua_getglobal(L, "pprint");
if (lua_isnil(L, -1)) {
lua_pop(L, 1);
lua_getglobal(L, "print");
}
lua_insert(L, 1);
if (lua_pcall(L, lua_gettop(L) - 1, 0, 0) != 0) {
l_message(
lua_pushfstring(L, "error calling 'print' (%s)",
lua_tostring(L, -1)));
}
}
}
void TextGame::run()
@@ -87,21 +81,13 @@ void TextGame::run()
LuaConsole console;
while (true) {
console.add_stdin();
switch (console.state()) {
case LuaConsole::STATE_INCOMPLETE:
break;
case LuaConsole::STATE_COMPLETE:
int action = console.action();
if (action == LuaConsole::DO_COMMAND) {
doexp(viewer_.get_lua_state(), console.expression());
console.clear();
break;
case LuaConsole::STATE_SLASHCOMMAND:
} else if (action == LuaConsole::DO_SLASH) {
std::cerr << "Slash commands not supported yet." << std::endl;
console.clear();
break;
case LuaConsole::STATE_SYNTAX:
} else if (action == LuaConsole::DO_SYNTAX) {
std::cerr << console.syntax() << std::endl;
console.clear();
break;
}
}
}