Connect a Lua table to a C++ class without third party library/source

239 Views Asked by At

THIS IS NOT A DUPLICATE, read the full text!

I'm not sure if the title is the right but I will explain here in more detail.

I have a C++ class with some functions, variables and properties (C++ Builder). In Lua I have a simplified table reflecting the variables and properties.

Example:

class foo {
  private:
    // Other private members and functions

  public:
    int x;
    int y;
    String caption;
};

When I create an instance of the class foo I create and push a corresponding table onto lua global environment. I will have a global Lua table with all the instances but to simplify the example, we just skip the global table for now and focus on a single instance. Lua representation of the foo instance:

foo = { x, y, caption }

Now the "problem" at hand. In Lua the foo table is only a proxy for the C++ class instance, so when I do this in Lua...

foo.caption = "My caption"

...the C++ class instance of foo will set its variable caption. Same goes the other way around (Lua)...

print(foo.x)

...will print the value of the class instance foo's variable x.

I have Googled all day and most examples use other libraries and wrappers without explaining the mechanism behind it.

I have understood that I need to use meta tables and lightuserdata but does this mean I have to define getters/setters for each variable and use foo.GetX and foo.SetCaption to access them? That would be a lot of getter/setters.

Can someone explain how to do this connection between C++/Lua without using third party libraries/source?

EDIT: Updated title and made it clear that this isn't a duplicate as @Sombrero Chicken thinks.

0

There are 0 best solutions below