Add invoke_lua function to world model

This commit is contained in:
2021-10-15 14:47:12 -04:00
parent b7b4ad8577
commit 547b87d884
5 changed files with 84 additions and 62 deletions

View File

@@ -47,60 +47,6 @@ public:
static lua_State *globalL = NULL;
static void lstop(lua_State *L, lua_Debug *ar)
{
(void)ar; /* unused arg. */
lua_sethook(L, NULL, 0, 0);
/* Avoid luaL_error -- a C hook doesn't add an extra frame. */
luaL_where(L, 0);
lua_pushfstring(L, "%sinterrupted!", lua_tostring(L, -1));
lua_error(L);
}
static void laction(int i)
{
signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
terminate process (default action) */
lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
}
static void l_message(const char *msg)
{
fputs(msg, stderr);
fputc('\n', stderr);
fflush(stderr);
}
void TextGame::do_lua(const std::string &exp) {
assert(world_->stack_is_clear());
lua_State *L = world_->state();
// push the compiled function.
int status = luaL_loadbuffer(L, exp.c_str(), exp.size(), "=stdin");
assert(status == LUA_OK);
globalL = L;
signal(SIGINT, laction);
status = traceback_pcall(L, 0, LUA_MULTRET);
signal(SIGINT, SIG_DFL);
if (status == LUA_OK) {
if (lua_gettop(L) > 0) {
lfn_pprint_pprint(L);
lua_settop(L, 0);
}
} 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);
}
assert(world_->stack_is_clear());
}
void TextGame::do_view_command(const StringVec &cmd) {
if (cmd.size() != 1) {
std::cerr << "v command (view) takes no arguments" << std::endl;
@@ -154,6 +100,13 @@ void TextGame::do_choose_command(const StringVec &cmd) {
world_->invoke(inv);
}
void TextGame::do_lua(const std::string &exp) {
assert(world_->stack_is_clear());
InvocationData dummyresult;
Invocation inv(Invocation::KIND_LUA, actor_id_, actor_id_, exp, dummyresult);
world_->invoke(inv);
}
void TextGame::do_snapshot_command(const StringVec &cmd) {
if (cmd.size() != 1) {
std::cerr << "s command (snapshot) takes no arguments" << std::endl;