From 48cd8419bb274345fe386d47843f9aa16910e090 Mon Sep 17 00:00:00 2001 From: Clyne Sullivan Date: Wed, 27 Sep 2017 11:35:22 -0400 Subject: lua-scripted wandering --- include/components/wander.hpp | 12 ++++---- include/quest.hpp | 3 ++ include/systems/lua.hpp | 68 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 5 deletions(-) create mode 100644 include/systems/lua.hpp (limited to 'include') diff --git a/include/components/wander.hpp b/include/components/wander.hpp index 2001e89..d275158 100644 --- a/include/components/wander.hpp +++ b/include/components/wander.hpp @@ -1,16 +1,18 @@ #ifndef COMPONENTS_WANDER_HPP_ #define COMPONENTS_WANDER_HPP_ +#include + +#include + /** * Causes the entity to wander about. */ struct Wander { - Wander(float ix = 0, float r = 0) - : initialX(ix), range(r), countdown(0) {} + Wander(const std::string& s = "") + : script(LuaSystem::makeScript(s)) {} - float initialX; - float range; - int countdown; + LuaScript script; }; #endif // COMPONENTS_WANDER_HPP_ diff --git a/include/quest.hpp b/include/quest.hpp index 3358d8f..b42f756 100644 --- a/include/quest.hpp +++ b/include/quest.hpp @@ -78,6 +78,9 @@ public: titles.emplace_front(q.name); return titles; } + + static void save(void); + static void load(void); }; #endif // QUEST_HPP_ diff --git a/include/systems/lua.hpp b/include/systems/lua.hpp new file mode 100644 index 0000000..0d8528b --- /dev/null +++ b/include/systems/lua.hpp @@ -0,0 +1,68 @@ +#ifndef SYSTEMS_LUA_HPP_ +#define SYSTEMS_LUA_HPP_ + +#include +#include + +#include + +class LuaScript { +private: + lua_State* state; + std::string script; + +public: + LuaScript(const std::string& sc = "") + : script(sc) { + state = luaL_newstate(); + luaL_openlibs(state); + luaL_loadstring(state, script.c_str()); + lua_pcall(state, 0, 0, 0); + } + + inline auto operator()(void) { + lua_getglobal(state, "update"); + lua_pcall(state, 0, LUA_MULTRET, 0); + if (lua_gettop(state) != 2) + return vec2(); + vec2 ret (lua_tonumber(state, 1), lua_tonumber(state, 2)); + lua_pop(state, 2); + return ret; + } +}; + +class LuaSystem { +private: + class LuaInterpreter { + private: + lua_State* state; + + public: + LuaInterpreter(void) { + state = luaL_newstate(); + luaL_openlibs(state); + } + + void registerFunc(const std::string& name, lua_CFunction func) { + lua_pushcclosure(state, func, 0); + lua_setglobal(state, name.c_str()); + } + + void loadFile(const std::string& name) { + luaL_dofile(state, name.c_str()); + lua_pcall(state, 0, 0, 0); // 'prime' the file + } + + void runFunc(const std::string& name) { + lua_getglobal(state, name.c_str()); + lua_pcall(state, 0, 0, 0); + } + }; + +public: + inline static LuaScript makeScript(const std::string& s) { + return LuaScript(s); + } +}; + +#endif // SYSTEMS_LUA_HPP_ -- cgit v1.2.3