# How can I manage entities(in entity component system) using Lua scripts?

Suppose I have a code like this in C++

// Game.cpp
Entity* hero;
Entity* witch;
... // entity initialization

if(/player near witch/) {
if(hero->get<HealthComponent>()->getHealth() < 100) {
witch->get<GraphicsComponent>()->setAnimation("witch.heal");
hero->get<HealthComponent>()->setHealth(100);
}
else {
say("Go away!");
}
}


Suppose I want to put this code into Lua script, so I make an "interact" function in C++

void interact(Entity* first, Entity* second);


And call it like this:

interact(witch, hero);


Then I can call lua script, which gets first and second entity IDs and does something like this:

-- Script.lua
function interact(firstId, secondId)
if(getHealth(secondId) < 100) then
setAnimation(firstId, "witch.heal")
setHealth(secondId, 100)
else
say("Go away")
end
end


And then I can define wrapper functions in C++ like this

void setAnimation(int firstId, const std::string& animationName) {
Entity* e = entities[firstId];
e->get<GraphicsComponent>()->setAnimation(animationName);
}
// etc.


and call it from Lua. But this gets quite troublesome as I need to write lots of binding and wrapping(like "setAnimation") functions. Is there any other methods to control entitity behaviour using Lua?

• Find (or write) a library that automates the binding as much as possible. Do a search for "lua c++ binding" and you should find a lot on the subject. – glampert Jul 2 '14 at 1:07
• @glampert Maybe my question was not exactly clear,(I've edited my question) but my main question is: should I try to find a way for Lua to know about components or should I write wrapping functions like "setAnimation" in my example? – Elias Daler Jul 2 '14 at 6:31

Writing binding functions gets tiresome pretty fast, and is error prone. There are two ways I can think of on how to improve this:

1) Use some Lua wrapper code that creates the interface functions you need. I did see on your blog that you have used LuaWrapper. Not sure how much support that lib have but there are others that use templates to create the binding functions. For my own project, I wrote my own system that also have the name LuaW. This is an example of what my code looks like. All objects are managed (created/destroyed) in the C++ code:

C++ side:

LuaW_Class<CameraComponent>( scriptEngine->m_pkState, "CameraComponent");
LuaW_ClassFunction(scriptEngine->m_pkState, "CameraComponent", "GetName", &CameraComponent::GetName);
LuaW_ClassFunction(scriptEngine->m_pkState, "CameraComponent", "GetCamera", &CameraComponent::GetCamera);

LuaW_RegisterGlobal<World>(scriptEngine->m_pkState, "World", m_world.get());


Lua side:

local cament = World:MainScene():CreateEntity("blueprints/camfront.blueprint", Vector3:new(0,0,0) )
camcomp = cament:GetComponent("CameraComponent")