Files
integration/luprex/cpp/luaconsole.cpp

87 lines
2.0 KiB
C++
Raw Normal View History

2021-01-23 16:10:29 -05:00
#include <string.h>
#include "luaconsole.hpp"
LuaConsole::LuaConsole() {
lua_state_ = lua_open();
clear();
}
LuaConsole::~LuaConsole() {
lua_close(lua_state_);
}
void LuaConsole::clear() {
2021-01-23 20:12:21 -05:00
expression_ = "";
2021-01-23 16:10:29 -05:00
lines_ = 0;
2021-01-23 20:12:21 -05:00
syntax_ = "";
action_ = DO_NOTHING;
2021-01-23 16:10:29 -05:00
}
void LuaConsole::add(std::string line) {
2021-01-23 20:12:21 -05:00
if (action_ != DO_NOTHING) {
clear();
}
2021-01-23 16:10:29 -05:00
for (int i = 0; i < int(line.size()); i++) {
if (line[i] == '\n') line[i] = ' ';
}
expression_ += line;
expression_ += '\n';
lines_ += 1;
// Convert leading = to 'return'
if (expression_[0] == '=') {
expression_ = std::string("return ") + expression_.substr(1);
}
// Analyze slash-commands.
if (expression_[0] == '/') {
if (lines_ == 1) {
2021-01-23 20:12:21 -05:00
action_ = DO_SLASH;
2021-01-23 16:10:29 -05:00
syntax_ = "";
} else {
2021-01-23 20:12:21 -05:00
action_ = DO_SYNTAX;
2021-01-23 16:10:29 -05:00
syntax_ = "slash command has more than one line";
}
return;
}
// Analyze lua expressions.
int top = lua_gettop(lua_state_);
int status = luaL_loadbuffer(lua_state_, expression_.c_str(), expression_.size(), "=stdin");
if (status == LUA_ERRSYNTAX)
{
const char *eof = "'<eof>'";
size_t lmsg;
const char *msg = lua_tolstring(lua_state_, -1, &lmsg);
const char *tp = msg + lmsg - (sizeof(eof) - 1);
if (strstr(msg, eof) == tp) {
syntax_ = "";
2021-01-23 20:12:21 -05:00
action_ = DO_NOTHING;
2021-01-23 16:10:29 -05:00
} else {
syntax_ = msg;
2021-01-23 20:12:21 -05:00
action_ = DO_SYNTAX;
2021-01-23 16:10:29 -05:00
}
} else {
syntax_ = "";
2021-01-23 20:12:21 -05:00
action_ = DO_COMMAND;
2021-01-23 16:10:29 -05:00
}
lua_settop(lua_state_, top);
}
void LuaConsole::add_stdin() {
2021-01-23 20:12:21 -05:00
if (action_ != DO_NOTHING) {
clear();
}
2021-01-23 16:10:29 -05:00
const int MAXINPUT = 1000;
char buf[MAXINPUT];
fputs(expression_.empty() ? "> " : ">> ", stdout);
fflush(stdout);
if (fgets(buf, MAXINPUT, stdin)) {
size_t len = strlen(buf);
if (len > 0 && buf[len - 1] == '\n')
buf[len - 1] = '\0';
add(buf);
}
}