ThePhD / sol2

Sol3 (sol2 v3.0) - a C++ <-> Lua API wrapper with advanced features and top notch performance - is here, and it's great! Documentation:
http://sol2.rtfd.io/
MIT License
4.06k stars 492 forks source link

Missing documentation for using Sol to write Lua C libraries #1574

Open JRFarmer opened 5 months ago

JRFarmer commented 5 months ago

This is a follow-up, and generally a re-opening of this previous issue: https://github.com/ThePhD/sol2/issues/222

Sol can be used to implement C libraries. I understand from the previous issue linked above it is not the intended scope of Sol, but it is possible and would be helpful to document this unintentional feature.

You will see in my example below that I use existing Sol features and API to implement a C library. In this case, I'm just making some hypothetical C++ functions callable from Lua.

Obviously there's no need to document every scenario and use case (Sol's doc is already quite complete in this respect), but providing a simple demonstration of the capability and a working example would help others.

#include <sol/sol.hpp>

extern void foo(void);
extern int bar(int val);
extern std::string bas(const std::string& val);
extern double bat(double val);

extern "C" int luaopen_app(lua_State *L)
{
    sol::state_view lua(L);
    sol::table app = lua.create_table_with(
        "foo", &foo,
        "bar", &bar,
        "bas", &bas,
        "bat", &bat
    );

    sol::stack::push(L, app);
    return 1;
}
ThePhD commented 5 months ago

You're right, we only have 2 requires examples and probably need a basic "Create C library" version of that. This will probably work for that, but I'd need to set up a small CMake app that'll compile this as a static lib and then open it from a library and then make sure it works across lua versions.

One more thing on the list of things to do...

JRFarmer commented 5 months ago

I'd need to set up a small CMake app that'll compile this as a static lib

In my tinkering, I had been compiling my example code as a shared object and let Lua's C library loader find the .so and load it. And of course I'm using CMake to build it. I might clean it up well enough to send you a PR.