Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expose C++ unions to Lua

Tags:

c++

unions

lua

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)

like image 290
Orfby Avatar asked Aug 03 '15 20:08

Orfby


People also ask

What is Lua Userdata?

The lua_newuserdata function allocates a block of memory with the given size, pushes the corresponding userdatum on the stack, and returns the block address.

How does Lua stack work?

3.1.Lua uses a virtual stack to pass values to and from C. Each element in this stack represents a Lua value ( nil , number, string, etc.). Whenever Lua calls C, the called function gets a new stack, which is independent of previous stacks and of stacks of C functions that are still active.

What is a Lua state?

The lua_State is basically a way to access what's going on in the Lua "box" during execution of your program and allows you to glue the two languages together.


1 Answers

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!

like image 145
Samane Avatar answered Sep 30 '22 17:09

Samane