Created basic ecs that has an optional lua module
This commit is contained in:
29
ecs-lua/include/ecs-lua.h
Normal file
29
ecs-lua/include/ecs-lua.h
Normal file
@@ -0,0 +1,29 @@
|
||||
#pragma once
|
||||
|
||||
#include "sol.hpp"
|
||||
#include "ecs.h"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
namespace ecs::lua {
|
||||
struct LuaWrapper : Component {
|
||||
LuaWrapper(sol::object object) : _object(object) {}
|
||||
|
||||
sol::object _object;
|
||||
};
|
||||
|
||||
template <typename T, typename... Constructor, typename... Args>
|
||||
void register_component(sol::state& lua, Args... args) {
|
||||
lua.new_usertype<T>(get_typename<T>(),
|
||||
"new", sol::factories([](Constructor... constructor) {
|
||||
return new T(constructor...);
|
||||
}), args...
|
||||
);
|
||||
lua.set_function("_internal_to_" + get_typename<T>(), [] (Component* component) {
|
||||
return (T*)component;
|
||||
});
|
||||
}
|
||||
|
||||
void init(sol::state& lua);
|
||||
}
|
||||
|
||||
50
ecs-lua/src/ecs-lua.cpp
Normal file
50
ecs-lua/src/ecs-lua.cpp
Normal file
@@ -0,0 +1,50 @@
|
||||
#include "ecs-lua.h"
|
||||
|
||||
namespace ecs::lua {
|
||||
void init(sol::state& lua) {
|
||||
sol::table ecs = lua.create_table("ecs");
|
||||
|
||||
ecs.new_usertype<Entity>("Entity",
|
||||
"add_component", [] (Entity* thiz, std::string name, Component* component) {
|
||||
return thiz->add_component(name, component);
|
||||
},
|
||||
"has_components", [] (Entity* thiz, sol::variadic_args args) {
|
||||
std::vector<std::string> names;
|
||||
for (std::string name : args) {
|
||||
names.push_back(name);
|
||||
}
|
||||
return thiz->has_components(names);
|
||||
},
|
||||
"get_component", [&lua] (Entity* thiz, std::string name) -> sol::object {
|
||||
// Convert to the correct component type
|
||||
auto f1 = lua["_internal_to_" + name];
|
||||
if (f1.valid()) {
|
||||
return f1(thiz->get_component(name));
|
||||
}
|
||||
|
||||
// If the type of the component unknown we assume it a lua object and convert it to the wrapper
|
||||
auto f2 = lua["_internal_to_LuaWrapper"];
|
||||
return f2(thiz->get_component(name));
|
||||
}
|
||||
);
|
||||
|
||||
ecs.new_usertype<View<>>("View",
|
||||
"for_each", &View<>::for_each
|
||||
);
|
||||
|
||||
ecs.new_usertype<Manager>("Manager",
|
||||
"create_entity", &Manager::create_entity,
|
||||
"view", [] (Manager* thiz, sol::variadic_args args) {
|
||||
std::vector<std::string> names;
|
||||
for (std::string name : args) {
|
||||
names.push_back(name);
|
||||
}
|
||||
return thiz->view(names);
|
||||
}
|
||||
);
|
||||
|
||||
register_component<LuaWrapper, sol::object>(lua,
|
||||
"object", &LuaWrapper::_object
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user