ecs/ecs-lua/src/ecs-lua.cpp

62 lines
1.7 KiB
C++

#include "ecs-lua.h"
#include "ecs.h"
namespace ecs::lua {
void init(sol::state& lua) {
// Add a preloader that loads all the ecs stuff
sol::table preload = lua["package"]["preload"];
preload["ecs"] = [&lua] {
sol::table ecs = lua.create_table();
ecs.new_usertype<Entity>("Entity",
"__tostring", [] (Entity* thiz) {
return uuids::to_string(thiz->uuid);
},
"add_component", [] (Entity* thiz, Component* component, std::string name) {
return thiz->add_component(ComponentID::get_id({name})[0], 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(ComponentID::get_id(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(ComponentID::get_id({name})[0]));
}
throw std::runtime_error("Unknown component");
}
);
ecs.new_usertype<View<>>("View",
"for_each", &View<>::for_each
);
ecs.new_usertype<Manager>("Manager",
"create_entity", [] (Manager* thiz) {
// @todo Allow to construct with given uuid
return thiz->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(ComponentID::get_id(names));
}
);
register_component<Wrapper, std::string, sol::object>(lua, ecs,
"name", &Wrapper::name,
"table", &Wrapper::table
);
return ecs;
};
}
}