summaryrefslogtreecommitdiffstats
path: root/src/control/ScriptContext.hpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/control/ScriptContext.hpp')
-rw-r--r--src/control/ScriptContext.hpp63
1 files changed, 21 insertions, 42 deletions
diff --git a/src/control/ScriptContext.hpp b/src/control/ScriptContext.hpp
index 86c8c0f..f9f8445 100644
--- a/src/control/ScriptContext.hpp
+++ b/src/control/ScriptContext.hpp
@@ -36,6 +36,7 @@ extern "C" {
#include <memory>
#include <string>
+#include <unordered_set>
namespace RPGEdit {
@@ -46,43 +47,25 @@ class ScriptContext {
private:
lua_State *L;
- void setupEnv() {
- const std::pair<const char *, lua_CFunction> libs[] = {
- {"_G", luaopen_base},
- {"bit32", luaopen_bit32},
- {"math", luaopen_math},
- {"string", luaopen_string},
- {"table", luaopen_table},
- };
-
- for (auto &lib : libs) {
- luaL_requiref(L, lib.first, lib.second, 1);
- lua_pop(L, 1);
- }
-
- for (const char *f : {"dofile", "loadfile", "require"}) {
- lua_pushnil(L);
- lua_setglobal(L, f);
- }
- }
+ std::unordered_set<std::string> loadedScripts;
- void cleanupEnv() {
- lua_pushglobaltable(L);
+ void setupEnv();
+ void cleanupEnv();
- lua_pushnil(L);
- lua_setmetatable(L, -2);
+ void load(const std::string &script);
- lua_pushnil(L);
- while (lua_next(L, -2) != 0) {
- lua_pop(L, 1);
+ size_t pushArgs() {
+ return 0;
+ }
- lua_pushvalue(L, -1);
+ template<typename... Args>
+ size_t pushArgs(Model::ScriptValue *v, Args ...args) {
+ if (v)
+ v->push(L);
+ else
lua_pushnil(L);
- lua_rawset(L, -4);
- }
-
- lua_pop(L, 1);
+ return pushArgs(args...) + 1;
}
public:
@@ -107,25 +90,21 @@ public:
lua_setglobal(L, key.c_str());
}
- void load(const std::string &name) {
- std::string filename = "../resources/script/" + name + ".lua";
+ template<typename... Args>
+ void run(const std::string &script, const std::string &name, Args ...args) {
+ load(script);
- lua_rawgetp(L, LUA_REGISTRYINDEX, this);
- lua_pushstring(L, name.c_str());
- luaL_loadfile(L, filename.c_str());
- lua_rawset(L, -3);
- lua_pop(L, 1);
- }
-
- void run(const std::string &name) {
setupEnv();
lua_rawgetp(L, LUA_REGISTRYINDEX, this);
- lua_getfield(L, -1, name.c_str());
+ lua_getfield(L, -1, script.c_str());
lua_remove(L, -2);
lua_call(L, 0, 0);
+ lua_getglobal(L, name.c_str());
+ lua_call(L, pushArgs(args...), 0);
+
cleanupEnv();
}
};