From 41addc2d6b600e9cade63884de1c13dba662dc31 Mon Sep 17 00:00:00 2001 From: Andy Belle-Isle Date: Wed, 28 Aug 2019 23:45:35 -0400 Subject: Can now create entities using Lua scripting --- src/main.cpp | 63 +++++++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 41 insertions(+), 22 deletions(-) (limited to 'src/main.cpp') diff --git a/src/main.cpp b/src/main.cpp index 266519c..57a4efb 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -148,27 +148,45 @@ struct Position : entityx::Component float x,y; }; +using namespace entityx; +using namespace entityx::lua; +namespace lb = luabridge; -void LuaTest(void) +EventManager events; +EntityManager entities(events); + +lua_State* L; + +lb::LuaRef spawn(lb::LuaRef ref) { - using namespace entityx; - using namespace entityx::lua; - namespace lb = luabridge; + lb::LuaRef entity(L); + entity = lb::newTable(L); - std::function ctor = [](float x, float y) { - return Position(x, y); - }; + if (ref.isTable()) { + + Entity e = entities.create(); + + for (auto &&comp : lb::pairs(ref)) { + if (comp.first.cast() == "Position") { + float x = comp.second["x"]; + float y = comp.second["y"]; + entity["Position"] = e.assign(x, y).get(); + } else if (comp.first.cast() == "init") { + entity["init"] = comp.second; + } + } + } else { + std::cerr << "Parameter to spawn() must be a table!" << std::endl; + } + + return entity; +} - ctor(6,7); - //export_component("Position", ctor, - // [](MemberRegister& m) { - // m.add("x", &Position::x); - // m.add("y", &Position::y); - // } - //); +void LuaTest(void) +{ - lua_State* L = luaL_newstate(); + L = luaL_newstate(); luaL_openlibs(L); lb::getGlobalNamespace(L). @@ -180,16 +198,17 @@ void LuaTest(void) .endClass() .endNamespace(); - setup_entityx_api(L); - - std::shared_ptr events(new EventManager()); - std::shared_ptr entities(new EntityManager(*events)); - new_entity_manager(L, entities, "manager"); + lb::getGlobalNamespace(L) + .beginNamespace("game") + .addFunction("spawn", spawn) + .endNamespace(); - if (luaL_dofile(L, "Scripts/init.lua")) { - std::cout << "Lua Error: " << lua_tostring(L, -1) << std::endl; + if (luaL_dofile(L, "Scripts/init.lua")) + { + std::cout << "Lua error: " << lua_tostring(L, -1) << std::endl; } + entities.each([&](Entity e, Position& p){ (void)e;std::cout << p.x << std::endl;}); lua_close(L); } -- cgit v1.2.3