Advertisement

Lua: call lua function from C++ object

Started by July 30, 2004 02:36 PM
0 comments, last by Lacutis 20 years, 3 months ago
OK, I've been driving myself crazy trying to figure out how to pass a pointer (from objects that I have created on the C++ side) to functions in the Lua script. I know that everyone here will probably tell me to use luaBind or one of the other tools but I'd prefer to figure this out on my own without using luaBind or similar. A simple example might be the following:

//
// C++ class
//
class cGameObject
{
protected:
	ULONG	m_ObjectID;
public:
	cGameObject() : m_ObjectID(0)
	{
	}
	~cGameObject()
	{
	}
};

so, in game code, I might have a factory or some other mechanism that creates game objects, but here I just new the pointer:

...

	cGameObject* pGO = new cGameObject();


now, I think that I have figured out how to create userdata that Lua will know about, like so:

	cGameObject** ptr = (cGameObject**)lua_boxpointer(luaVM, pGO);

so lets say that I have a Lua script that will perform some operation on the cGameObject, in this example, set the object id:

    function GameObject:SetObjectID()
      self.m_ObjectID = NewObjectID()    // NewObjectID() is an exposed function from C++
    end

so, with all those things in place I now need to know how to be able to call the Lua function SetObjectID() from my C++ created object. Any help is appreciated!
Dave Dak Lozar Loeser
"Software Engineering is a race between the programmers, trying to make bigger and better fool-proof software, and the universe trying to make bigger fools. So far the Universe in winning."--anonymous
For something like an object factory I would *strongly* suggest creating the objects from the lua side, and not the C++ side. Especially if they are going to be scripted objects.

Saying that, this is what you need to know.

In order to have a c++ object that can be acted upon by Lua you need to create a userdata, and a metatable for your objects.

I could copy and paste an example, but its probably better if you read it from the Lua book:
"User defined types in C"
http://www.lua.org/pil/28.html

The part you will need to get from C to C++ is like so.

In C you go:

static int lua_SetObjectId(lua_State *l)
{
cGameObject *GameObj = (cGameObject *)lua_touserdata(L,1); // pulls out your C++ object from the userdata

GameObj->SetObjectId(lua_checkint(L,2);

return 0; // no return values for lua.
}

And make sure in your new function for the gameobject class you bind the setobjectid function into your metatable like the book shows.

Thats really all there is to it.

This topic is closed to new replies.

Advertisement