Here is how i made it possible to call C++ from LUA.
I want to build Multiplayer game in Leadwerks. But i couldn't find networking libraries and threading libraries that would make it usable in Lua. So i build a Networking client in C++ with libcurl and libpthread . But i want to still use the Lua scripting on the prefabs since a lot of work is already done for me here. And also programming in Higher level languages is just faster.
I decided to use the libtolua++ libraries, since this is already build into Leadwerks.
I work on Ubuntu 15.04. Here the tolua++ libs are installed with:
sudo apt-get install libtolua++5.1-dev
The tolua++ program needs a pck file which shall contain the c++ like seudo code that is translated into lua classes.
My package:
$#include "shot.h"
class ShotListener {
ShotListener();
~ShotListener();
void shot(Object* oEntity, float damage);
float getHealth(Object* oEntity);
};
I have made two functions. One to emit shots detected on the Entities from the Lua scripting. Another to get the current health status from C++ side.
My actual ShotListener.h class looks like this:
#pragma once
#include "App.h"
#include "Leadwerks.h"
using namespace Leadwerks;
class ShotListener {
private:
public:
ShotListener(void) {
}
~ShotListener(void){}
void shot(Object* oEntity, float damage) {
App *app = App::getInstance();
Entity * entity = (Entity*)oEntity;
app->entityShot(entity, damage);
return;
}
float getHealth(Object* oEntity) {
App *app = App::getInstance();
Entity * entity = (Entity*)oEntity;
float value = app->getEntityHealth(entity);
return value;
}
};
As you can see i changed the default App class into a Singleton so that i can get the App object from the instances of ShotListener that is used from Lua.
Having placed these two files in the same folder i ran the following function from the terminal:
tolua++5.1 -o tolua_shot.cpp -H tolua_shot.h -n Shot shot.pkg
This generated two files tolua_shot.cpp and tolua_shot.h that i included in my C++ project along with the shot.h file.
This way i can do a
self.shotListener = ShotListener:new()
In the Script:Start() function in mu Lua objects
and a
self.shotListener:shot(self.entity, self.hits)
When Hurt is called in the Lua object.
After this i just had to sort out all the Segmentation error bugs because of multithreading.
I forgot to mention that the ShotListener Lua also needs to be initialized in the main.cpp before app->Start() with the following:
if (Interpreter::L==NULL) Interpreter::Reset();
tolua_ShotListener_open(Interpreter::L);