In C ++, let's say I have a class that creates a binary tree similar to a structure, and I use it something like this:
CTreeRoot* root = new CTreeRoot(); CNode* leftNode = root->getLeftNode(); CNode* rightNode = root->getRightNOde(); leftNode->doSomething(); rightNode->doSomething();
And suppose that the left and right nodes have their left and right nodes (hence the binary tree). Now I want to show this to Lua ( not using luabind) so that I can do the same:
local root = treeroot.new(/* whatever */) local left = root:getLeftNode() local right = root:getRightNode() left:doSomething(); right:doSomething();
I got most of the work. However, for the getLeftNode () and getRightNode () methods, I am sure that I am doing this "wrong." This is how I implement getLeftNode () in C ++, for example:
int MyLua::TreeRootGetLeftNode(luaState* L) { CTreeRoot* root = (CTreeRoot*)luaL_checkudata(L, 1, "MyLua.treeroot"); CNode* leftNode = root->getLeftNode(); if (leftNode != NULL) { int size = sizeof(CNode);
I threw UserData back to the CTreeRoot object, call getLeftNode (), make sure it exists, and then (here the "wrong part") create another USERDATA data object with the copy constructor copy object I want to return.
Is this "standard practice" for this type of scenario? It looks like you would like to avoid creating another copy of the object, because what you really want is just a reference to an existing object.
It seems like this would be an ideal place for lightuserdata, since I do not want to create a new object, I would be happy to return an existing object. The problem, however, is that lightuserdata does not have a meta table, so the objects will be useless to me as soon as I return them. Basically, I want to do something like:
int MyLua::TreeRootGetLeftNode(luaState* L) { CTreeRoot* root = (CTreeRoot*)luaL_checkudata(L, 1, "MyLua.treeroot"); CNode* leftNode = root->getLeftNode(); if (leftNode != NULL) {
Can someone tell me how I can return the MyLua::TreeRootGetLeftNode to a Lua copy of an object that already exists in such a way that I can use this object as an “object” in Lua?