]> code.bitgloo.com Git - clyne/gamedev2.git/commitdiff
cleaned up lua function bindings
authorClyne Sullivan <clyne@bitgloo.com>
Tue, 1 Oct 2019 12:37:05 +0000 (08:37 -0400)
committerClyne Sullivan <clyne@bitgloo.com>
Tue, 1 Oct 2019 12:37:05 +0000 (08:37 -0400)
src/engine.cpp
src/script.cpp
src/script.hpp

index b1d9a562f20552676ca8aa5f0085e966c1e45acf..81e0272c188b789e8bb541cd76083deb86b24ca2 100644 (file)
@@ -59,13 +59,11 @@ int Engine::init(void)
     // Load game script and entity data
     auto* script = systems.system<ScriptSystem>().get();
     script->addToGameNamespace("loadFont",
-    [this](std::string name, std::string file, int size) {
-        systems.system<TextSystem>().get()->loadFont(name, file, size);
-    });
+        bindInstance(&TextSystem::loadFont,
+                     systems.system<TextSystem>().get()));
     script->addToGameNamespace("puts",
-    [this](std::string name, float x, float y, std::string text) {
-        systems.system<TextSystem>().get()->put(name, x, y, text);
-    });
+        bindInstance(&TextSystem::put,
+                     systems.system<TextSystem>().get()));
     script->init();
     
 
index 6cda627d2d8f41418ef1ea2c17c275bc8f068040..0f940d3f0515f188f149c5b37ba07401c0d530c2 100644 (file)
@@ -87,12 +87,6 @@ void ScriptSystem::doFile(void)
 
 void ScriptSystem::scriptExport(void)
 {
-    std::function<sol::table(sol::table)> entitySpawn = 
-        [this](sol::table t){ return spawn(t);};
-
-    std::function<World* (sol::object)> worldRegister =
-        [this](sol::object t){ return worldSystem.addWorld(t); };
-
     lua.new_usertype<Position>("Position",
             sol::constructors<Position(double x, double y), Position()>(),
             "x", &Position::x,
@@ -137,8 +131,9 @@ void ScriptSystem::scriptExport(void)
             "getSize", &World::getSize);
 
     game = lua["game"].get_or_create<sol::table>();
-    game.set_function("spawn", entitySpawn);
-    game.set_function("worldRegister", worldRegister);
+    game.set_function("spawn", bindInstance(&ScriptSystem::spawn, this));
+    game.set_function("worldRegister", bindInstance(&WorldSystem::addWorld,
+                                                    &worldSystem));
 }
 
 sol::table ScriptSystem::spawn(sol::object param)
index 0ac9e639d275b62f09895077394d80addcb3096e..24cc14255bf0b836d1d4c8a25e8113437844c7a5 100644 (file)
 
 #include "world.hpp"
 
+/**
+ * Utility for pairing class instances to their member function calls.
+ * This is useful for adding functions to the Lua game namespace.
+ *
+ * @param func The member function to call
+ * @param instance The instance to bind to
+ * @return A function that calls the member function using the given instance
+ */
+template<class C, typename R, typename... Args>
+auto bindInstance(R (C::* func)(Args...), C *instance)
+{
+    return [instance, func](Args... args) { (instance->*func)(args...); };
+}
+
+
 struct EntitySpawnEvent
 {
     sol::object ref;