81 lines
1.9 KiB
C++
81 lines
1.9 KiB
C++
|
|
#include <string.h>
|
|
#include "luaconsole.hpp"
|
|
|
|
LuaConsole::LuaConsole() {
|
|
lua_state_ = lua_open();
|
|
clear();
|
|
}
|
|
|
|
LuaConsole::~LuaConsole() {
|
|
lua_close(lua_state_);
|
|
}
|
|
|
|
void LuaConsole::clear() {
|
|
expression_="";
|
|
lines_ = 0;
|
|
syntax_="";
|
|
state_=STATE_INCOMPLETE;
|
|
}
|
|
|
|
void LuaConsole::add(std::string line) {
|
|
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) {
|
|
state_ = STATE_SLASHCOMMAND;
|
|
syntax_ = "";
|
|
} else {
|
|
state_ = STATE_SYNTAX;
|
|
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_ = "";
|
|
state_ = STATE_INCOMPLETE;
|
|
} else {
|
|
syntax_ = msg;
|
|
state_ = STATE_SYNTAX;
|
|
}
|
|
} else {
|
|
state_ = STATE_COMPLETE;
|
|
syntax_ = "";
|
|
}
|
|
lua_settop(lua_state_, top);
|
|
}
|
|
|
|
void LuaConsole::add_stdin() {
|
|
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);
|
|
}
|
|
}
|