How to expose C++ unions to Lua

纵饮孤独 提交于 2019-12-22 04:38:14

问题


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.



来源:https://stackoverflow.com/questions/31796626/how-to-expose-c-unions-to-lua

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!