Use C++ library object from within Lua

Viewed 829

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:

  1. create a library containing, for example, a class 'Player' in C++
  2. modify this library to be usable from Lua
  3. 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.

2 Answers

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

Related