I’m an absolute beginner when it comes to using both SWIG and lua, and a mediocre C++ developer, and I just don’t seem to understand how I can bind C++ classes with Lua.
My end goal is to have an instance of a class, pass it to my lua script which manipulates that object in a certain way, then I retrieve that object in c++ and do whatever else I want to do with it.
So… I’ve downloaded Lua and C++, compiled a few examples, I am able to run some lua script in my c++ program. So far so good.
Now, I’ve downloaded SWIG. I’m using VC2010 on Windows 7. From what I understand I’m suppose to create an interface file. So I’ve created one, example.i:
%module creature
class Creature
{
public:
Creature(void);
Creature(int id);
~Creature(void);
(...) the rest of my class here
(Just added %module creature to my Creature.h and saved it as creature.i). I ran SWIG using
swig -c++ -lua creature.i
and got my creature.cxx file.
Now, I’ll probably embarrass myself now but… I don’t know what to do next. Am I suppose to build the output file somehow? How can I use it now? I’ve read here http://www.swig.org/Doc1.3/Lua.html that I need to link the generated file (*.cxx) with the rest of my code (so I do that by simply including the file in my project and adding the line #include “Creature.h”). But when I compile I get errors like
error C2065: 'LUA_GLOBALSINDEX' : undeclared identifier
error C2036: 'const luaL_reg *' : unknown size
I have also tried compiling it using MinGW but I get the same problem. It would be great if someone could show me an example or a step-by-step tutorial of how I can use these tools together, as I have a hard time grasping the whole idea. This is definitely due to my lack of understanding of the basics of how this should be used so please be gentle to a noob.
Any help will be much appreciated.
SWIG is a tool for linking scripting languages to C or C++ code. It works as a preprocess step: you run the SWIG executable on a .swig file, which produces a bit of C or C++ code. You then build that code into whatever project you want to do the linking to that scripting language for.
SWIG’s Lua support is most certainly not compatible with Lua 5.2. Indeed, you will find very little code out there that is compatible with Lua 5.2. If you want to actually do something with Lua code, stick with 5.1 at least for the time being.