How to expose C++ unions to Lua

2019-04-26 21:23发布

问题:

For a project I'm working on, I need to expose some C++ classes in another library to Lua. Unfortunately, one of the most important classes in this library has lots of Unions and Enums (the sf::Event class from SFML), and from a quick Google search I've discovered there is nothing on exposing C++ Unions to Lua. I don't mind if it's being exposed with the Lua/C API, with a library or with a binding generator, as long as it works. But, I'd prefer not to use a binding generator, because I want to be able to create an object in C++, then expose that instance of the object to Lua (unless that's possible with a binding generator)

回答1:

For registering C/C++ functions you need to first make your function look like a standard C function pattern which Lua provides:

extern "C" int MyFunc(lua_State* L)
{
    int a = lua_tointeger(L, 1); // First argument
    int b = lua_tointeger(L, 2); // Second argument
    int result = a + b;

    lua_pushinteger(L, result);

    return 1; // Count of returned values
}

Every function that needs to be registered in Lua should follow this pattern. Return type of int , single parameter of lua_State* L. And count of returned values. Then, you need to register it in Lua's register table so you can expose it to your script's context:

lua_register(L, "MyFunc", MyFunc);

For registering simple variables you can write this:

lua_pushinteger(L, 10);
lua_setglobal(L, "MyVar");

After that, you're able to call your function from a Lua script. Keep in mind that you should register all of your objects before running any script with that specific Lua state that you've used to register them.

In Lua:

print(MyFunc(10, MyVar))

Result:

20

I guess this could help you!



回答2:

If you are willing to use boost::variant rather than a union, you could try using my LuaCast library.

I'll try to add unions as a base type as well.



标签: c++ lua unions