Convert Lua code to C++ classes back in C++ - c++

I've seen similar posts but none that quite asked the question in the same way.
Basically, I've been playing with Shiva3d lately ( http://www.stonetrip.com/ ), which is a 3d engine. The coding inside the engine is in Lua, however, the actual product when exported from the IDE is C++ code. While the coding is restricted, it does a fair job at exporting function, variables and everything back in C++ code.
What I want to know is, can I create a base engine, where there would be a set of predefined class and then use Lua to extend/overload these base classes (by providing certain predefined required functions) and get that code back in C++ with the different Lua/C++ binding libraries that exist?

Have a look at SWIG http://www.swig.org/
It parses the C++ headers and creates binding for several languages (including Lua).

Although I really like SWIG, I fell in love with luabind, because you have more direct control. Additionally it provides a built-in object orientation system and you do not need an additional translator/compiler like swig.

Related

Use C++ library object from within Lua

So for the past few hours I've been trying to figure out how to use C++ classes contained in static (or dynamic) libraries from within Lua. I've found several packages, such as LunaFive or SimpleCppBinding, but I seem not to understand how to use them properly. From what I see there's a main function, therefore I guess it's not a library, but an executable which I run and then run the Lua script, which will hook the app and get the class, or something? What I basically want to do is:
create a library containing, for example, a class 'Player' in C++
modify this library to be usable from Lua
somehow use this class and it's methods from within the Lua in the same way as if it would be a Lua class
Is such thing even possible? And if so, could someone explain how such thing can be done?
I'm currently on Windows, but I can do it on Linux as well. On windows I'm using VS, on Linux I'd be using CLion paired with g++. Lua 5.3.
I'm not sure if this is somewhat relevant, but I'm developing a game-mode for FiveM (GTA V multiplayer client). The FiveM comes with a Lua support for scripting by default, but I'd love to use some of the C++ standard libraries and features. Therefore I'd really love to create some libraries for the server in C++, and then use them from within the Lua supplied by FiveM.
Static library: not possible. Your options are: 1. a dynamic library (binary) with some kind of interface accessible by Lua executable (Alien, Lua-specific hooks....) or 2. A custom executable which includes the Lua engine and the C++ stuff with some glue. Your examples with the 'main' function probably are the latter type.
Lua was designed, from the beginning, to be integrated with software written in C and other conventional languages. This duality of languages brings many benefits. Lua is a tiny and simple language, partly because it does not try to do what C is already good for, such as sheer performance, low-level operations, or interface with third-party software.
-Preface
I understand your pain, however Lua simply isn't meant to be used the way you intend, it's actually built to be used the other way around.
The closest thing I can think of to get the result what you want is to have a host C++ application from which you immediately create a lua state and push results of the functions you called from the C++ program into the stack, in return can be used in your Lua script and processed.
If this is something you might be able to adjust to, here is a great starting point

Generating API interfacing code for a scripting language from an existing C++ header file

I intend to use Squirrel as a scripting language for my C++ application. Naturally, there should be an API for interfacing with the C++ code (for things such as accessing and modifying attributes in my C++ program). This API would consist of a bunch of classes, enums and functions.
While there are utilities like Sqrat that make binding single C++ functions to a Squirrel VM the matter of a single line of code, that is still not satifactory: It would require me to create both the C++ classes with their functions to actually do all the interfacing work, and then I'd have to maintain all the bindings to make those C++ functions known in my scripts as well. My intention is to remove this double maintenance overhead.
So what I want is a tool that would simply take the already existing header file containing all my C++ classes and functions and generate API registration calls from this file. And while we are at it, of course it would be nice to automatically generate a documentation for every function as well (doesn't matter if it's HTML or just a Squirrel script that contains of function definitions + comments or whatever).
I know there's SWIG, but it doesn't have a binding Squirrel, and that's not exactly what I would be looking for anyway - after all, I need to create C++ wraper code, not Squirrel code. I've seen Flex, but I'm not sure whether that's what I'm looking for, either. So is there any tool that would do what I want (automate the creation of wrapper code and API documentation from a C/C++ header)? Otherwise, I guess I might have to write my own little C++ parser that can parse simple function and class definitions.

How to integrate c++ classes and objects around winApi?

Hey so for one of my c++ projects I need to develop a 4-5 window application.Now the issue is that currently all of my programs tasks are divided into classes, and I have tested them by passing 'dummy' values and returning print results. That's all fine and working, however now as I want to introduce a GUI interface it presents me with the problem of how my processing should communicate with the front end, since winAPI is initially meant for c and not object oriented language.
What I am thinking of doing, and have a feeling is going to be a tedious task, to make a class which does the win api's registrations and methods for me. Is there any other alternative to this ???
I was looking at integrating Qt into eclipse but I think they stopped providing the library for eclipse, because I couldn't find a download for the library anywhere, not even on the Qt download page.
Well, if you want to use Win32, then you have to do all the stuff that Win32 needs you to do. It's a rather low level API, so you just have to take care of a lot of details.
However, don't over-engineer things. You don't have to write a generic C++ wrapper for Win32... you just have to make a GUI for your program.
If your problem is only that classes are not supported by C, then simply replace the keyword class with the keyword struct. Just make sure to declare the access types of all variables (private, public, protected), that way it becomes interchangeable (Works for both). The only difference between them is the default access type, which for classes is private. In case you used other syntax that is unique to C++, then this wouldn't work.
There are code generators from C++ to C as well. The optimal solution would be to create a GUI using an IDE specifically for that purpose which uses C++ as its base language. MFC works well, but it is not open-source and you will need a considerable knowledge on inheritance and comfort with "class typecasting". Using the included wizards in Visual Studio will help.
Try the first option; it will possibly work the same way.

Scripting language for C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I'm getting a little rusty in scripting languages, provided they're popping like mushrooms lately :)
Today I thought that it would be nice to have a scripting language that talks seamlessly to C++, that is, could use C++ classes, and, the most important for me, could be compiled into C++ or some DLL/.SO (plus its .h) so that I could link it into my C++ program and make use of the classes the script defines or implements.
I know I could embed any popular scripting language such as lua, ruby, python... but the interface usually includes some kind of "eval" function that evaluates the provided scripting code. Depending on the tool used to couple C++ and the scripting language, the integration for callbacks of the script into C++ could be more or less easy to write, but I haven't seen any scripting language that actually allows me to write independent modules that are exposed as a .h and .so/dll to my program (maybe along the lines of a scripting language that generates C++ code).
Do you know any such tool/scripting language?
Thanks in advance.
PD. I've been thinking along the lines of Vala or Haskell's GHC. They generate C, but not C++...
UPDATE 2020: Today I would probably go with Lua + Sol2/3 except if I really want to avoid Lua as a language. Chaiscript becomes a good candidate in this case though it is not optimal performance-wise compared to Lua+Sol2/3 (though it was greatly improved through years so it is still good enough in many cases).
Falcon have been dead for some years, RIP.
The following ones are more C++ integration oriented than language bindings :
ChaiScript - trying at the moment in a little project, interesting, this one is MADE with C++ in mind and works by just including a header! Not sure if it's good for a big project yet but will see, try it to have some taste!
(not maintained anymore) Falcon - trying on a big project, excellent; it's not a "one include embed" as ChaiScript but it's because it's really flexible, and totally thought to be used in C++ (only C++ code in libs) - I've decided to stick with it for my biggest project that require a lot of scripting flexibility (comparable to ruby/python )
AngelScript - didn't try yet
GameMonkey - didn't try yet
Io - didn't try yet
For you, if you really want to write your scripting module in C++ and easily expose it to the scripting language, I would recommand going with Falcon. It's totally MADE in C++, all the modules/libraries are written that way.
The question usually asked in this context is: how do I expose my C++ classes so they can be instantiated from script? And the answer is often something like http://www.swig.org/
You're asking the opposite question and it sounds like you're complicating matters a bit. A scripting engine that produced .h files and .so files wouldn't really be a scripting engine - it would be a compiler! In which case you could use C++.
Scripting engines don't work like that. You pass them a script and some callbacks that provide a set of functions that can be called from the script, and the engine interprets the script.
Try lua: http://www.lua.org/
For using C++ classes in lua you can use:
To generate binding use tolua++: http://www.codenix.com/~tolua/
It takes a cleaned up header as input and outputs a c file that does the hard work. Easy, nice and a pleasure to work with.
For using Lua objects in C++ I'd take the approach of writing a generic Proxy object with methods like (field, setField, callMethod, methods, fields).
If you want a dll you could have the .lua as a resource (in Windows, I don't know what could be a suitable equivalent for Linux) and on your DllMain initialize your proxy object with the lua code.
The c++ code can then use the proxy object to call the lua code, with maybe a few introspection methods in the proxy to make this task easier.
You could just reuse the proxy object for every lua library you want to write, just changing the lua code provided to it.
This is slightly outside my area of expertise, but I'm willing to risk the downvotes. :-)
Boost::Python seems to be what you're looking for. It uses a bit of macro magic to do its stuff, but it does expose Python classes to C++ rather cleanly.
I'm the author of LikeMagic, a C++ binding library for the Io language. (I am not the author of Io.)
http://github.com/dennisferron/LikeMagic
One of my explicit goals with LikeMagic is complete and total C++ interoperability, in both directions. LikeMagic will marshal native Io types as C++ types (including converting between STL containers and Io's native List type) and it will represent C++ classes, methods, fields, and arrays within Io. You can even pass a block of Io code out of the Io environment and use it in C++ as a functor!!
Wrapping C++ types up for consumption in Io script is simple, quick and easy. Accessing script objects from C++ does require an "eval" function like you described, but the template based type conversion and marshaling makes it easy to access the result of executing a script string. And there is the aforementioned ability to turn Io block() objects into C++ functors.
Right now the project is still in the early stages, although it is fully operational. I still need to do things like document its build steps and dependencies, and it can only be built with gcc 4.4.1+ (not Microsoft Visual C++) because it uses C++0x features not yet supported in MSVC. However, it does fully support Linux and Windows, and a Mac port is planned.
Now the bad news: Making the scripts produce .h files and .so or .dll files callable from C++ would not only require a compiler (of a sort) but it would also have to be a JIT compiler. That's because (in many scripting languages, but most especially in Io) an object's methods and fields are not known until runtime - and in Io, methods can even be added and removed from live objects! At first I was going to say that the very fact that you're asking for this makes me wonder if perhaps you don't really understand what a dynamic language is. But I do believe in a way of design in which you first try to imagine the ideal or easiest possible way of doing something, and then work backwards from there to what is actually possible. And so I'll admit from an ease-of-use standpoint, what you describe sounds easier to use.
But while it's ideal, and just barely possible (using a script language with JIT compilation), it isn't very practical, so I'm still unsure if what you're asking for is what you really want. If the .h and .so/.dll files are JITted from the script, and the script changes, you'd need to recompile your C++ program to take advantage of the change! Doesn't that violate the main benefit of using script in the first place?
The only way it is practical would be if the interfaces defined the scripts do not change, and you just are making C++ wrappers for script functions. You'd end up having a lot of C++ functions like:
int get_foo() { return script.eval("get_foo()"); }
int get_bar() { return script.eval("get_bar()"); }
I will admit that's cleaner looking code from the point of view of the callers of the wrapper function. But if that's what you want, why not just use reflection in the scripting language and generate a .h file off of the method lists stored in the script objects? This kind of reflection can be easily done in Io. At some point I plan to integrate the OpenC++ source-to-source translator as a callable library from LikeMagic, which means you could even use a robust C++ code generator instead of writing out strings.
You can do this with Lua, but if you have a lot of classes you'll want a tool like SWIG or toLua++ to generate some of the glue code for you.
None of these tools will handle the unusual part of your problem, which is to have a .h file behind which is hidden a scripting language, and to have your C++ code call scripts without knowing that that are scripts. To accomplish this, you will have to do the following:
Write the glue code yourself. (For Lua, this is relatively easy, until you get into classes, whereupon it's not so easy, which is why tools like SWIG and toLua++ exist.)
Hide behind the interface some kind of global state of the scripting interpreter.
Supposing you have multiple .h files that each are implemented using scripts, you have to decide which ones share state in the scripting language and which ones use separate scripting states. (What you basically have is a VM for the scripting language, and the extremes are (a) all .h files use the same VM in common and (b) each .h file has its own separate, isolated VM. Other choices are more complicated.)
If you decide to do this yourself, writing the glue code to turn Lua tables into C++ classes (so that Lua code looks like C++ to the rest of the program) is fairly straightforward. Going in the other direction, where you wrap your C++ in Lua (so that C++ objects look to the scripts like Lua values) is a big pain in the ass.
No matter what you do, you have some work ahead of you.
Google's V8 engine is written in C++, I expect you might be able to integrate it into a project. They talk about doing that in this article.
Good question, I have often thought about this myself, but alas there is no easy solution to this kind of thing. If you are on Windows (I guess not), then you could achieve something like this by creating COM components in C++ and VB (considering that as a scripting language). The talking happens through COM interfaces, which is a nice way to interop between disparate languages. Same holds for .NET based languages which can interop between themselves.
I too am eager to know if something like this exists for C++, preferably open source.
You might check into embedding Guile (a scheme interpreter) or V8 (Google's javascript interpreter - used in Chrome - which is written in C++).
Try the Ring programming language
http://ring-lang.net
(1) Extension using the C/C++ languages
https://en.wikibooks.org/wiki/Ring/Lessons/Extension_using_the_C/C%2B%2B_languages
(2) Embedding Ring Interpreter in C/C++ Programs
https://en.wikibooks.org/wiki/Ring/Lessons/Embedding_Ring_Interpreter_in_C/C%2B%2B_Programs
(3) Code Generator for wrapping C/C++ Libraries
https://en.wikibooks.org/wiki/Ring/Lessons/Code_Generator_for_wrapping_C/C%2B%2B_Libraries

Pass variables between C++ and Lua via Swig

I'm working on a C++ project with a large number of classes (150+), each of which has anywhere from 10 to 300 fields or so. I would really like to be able to provide a scripting interface for testing purposes so that I can code callbacks that don't require any re-compilation. I'd like to do this in Lua since I'm more familiar with its C API than I am with Python's, but if it will save headaches I'd be happy to do it in Python.
I've got a solid grasp on how to call Lua functions from my C++ and vice versa, and I know how to pass basic data types back and forth. The question I have is how to share user-specified data types between the two using SWIG.
For example, at some point in my C++, I might want to evaluate a couple of pieces of member data in an object that has 250 fields. I'd like to be able to hand that object off to Lua which could then (hopefully?) use the generated SWIG wrappers to manipulate that object, display certain fields, and then pass the (potentially changed) object back to C++ for continued use.
I would also like to be able to instantiate an instance of the object in Lua using the wrappers and pass it off to C++ to be used as a normal C++ version of the object.
Is this possible? Could somebody point me towards a tutorial or an explicit example?
Thanks for any help you can offer!
As long as you wrap your user-defined types using Swig interfaces (see here for documentation on Swig-Lua API), the interaction should be seamless. The provided Swig wrappers will allow you to instantiate new objects, pass them along to C++ and vice-versa.
I do not believe that Swig-Lua wrapping supports director classes yet, which means that extending existing classes, instantiating them and passing them back to C++ is not possible. Directors are supported for languages such as Python, Java, C# though.
If swig gives you trouble, I've had good luck with the latest version of tolua++, which is for the sole purpose of binding C++ and Lua. It requires a modified .h file as input, which is a bit tedious, but no more so than Swig's modules. I have no reason to prefer one over the other, but it's good to know about both.
You should also check out Luabind. This one implements OOP for Lua and can map classes and data types from Lua back to C++.