How to directly map a Lua variable to a C++ variable?

By : Daerst

I am working on a game engine in C++ using Lua to define NPCs.

I can define a prototypic NPC like this:

orc =
    name = "Generic Orc",
    health = 100

function orc:onIdle()
    print("Orc idles...")

and then spawn an instance of "Orc" with entitySpawn(orc). This is a C++ function that reads values like health and name from the given table, creates an Entity object in C++ with the given values and in addition creates a Lua table for the specific NPC.

Now, I would like to have a direct connection between the variable in Lua and the mHealth member variable of the corresponding Entity object in C++, so I could assign a value in Lua and instantly use it in C++ and vice versa.

Is this even possible? Or do I have to make use of setter / getter functions? I have taken a look at light userdata and got to the point of storing a pointer to the C++ variable in Lua, but could not assign a value.

By : Daerst


I don't have time to give you any code, but keep in mind is the same as orc["health"]; that is, orc is a table and "health" is an element.

With that in mind, you can change the index and newindex metamethods of your table to have your own specific behavior. Store your "real" orc instance as some private metadata, then use it to update.

By : GManNickG

This video can help you solving your question :)
By: admin