Pointer from C++ to Lua/Tolua++ as an argument.

Started by
2 comments, last by Ashaman73 12 years, 1 month ago
Hello,
I'm new to Lua and during the last week I've delved into the language and the libraries that bind C++ classes and functions to Lua.
Right now I'm successfully using tolua++ 1.0.93 with Lua 5.1.
Scripts like this work flawlessly:

c = Class:new()
print("LUA: Num is "..c:getNum())
c:setNum(DEFINED_VAR)

But this kind of script is not what I need. I want to be able to pass a pointer to Class from inside the C++ code to a Lua function defined in the script and call Class' functions there, effectively manipulating the passed object.
I've searched a lot about how it should be done, but I'm still confused. As I'm using tolua I suppose I should use tolua_pushusertype to pass the pointer to the object to Lua. But I cannot understand how can I use the passed object's functions.
Tell me please what should I do to get the result I want? Any tips will be appreciated as I'm pretty tired from not being able to solve this problem on my own.

-upd-
Fixed Lua capitalization, thanks to dmail.
Advertisement
I don't think is possible using the raw pointer. The only way I can figure is to map the pointer to an ID with a std::map so that LUA use the ID and C++ know how to get the the pointer back from a MAP using the ID. but this will be slow and probably there's a better way to do that. (for example each LUA object is linked in someway to its corresponding C++ object

Peace and love, now I understand really what it means! Guardian Angels exist! Thanks!

"Lua" (pronounced LOO-ah) means "Moon" in Portuguese. As such, it is neither an acronym nor an abbreviation, but a noun. More specifically, "Lua" is a name, the name of the Earth's moon and the name of the language. Like most names, it should be written in lower case with an initial capital, that is, "Lua". Please do not write it as "LUA", which is both ugly and confusing, because then it becomes an acronym with different meanings for different people. So, please, write "Lua" right![/quote]
http://www.lua.org/about.html
What about lightuserdata in lua ? lightuserdata is a pointer, therefore you can easily transport any C/C++ pointer between lua and your C++ using these lightuserdata (I don't know tolua++, so I can't help you on this front).

You can use lua_pushlightuserdata to push an object from C++ on the stack and lua_touserdata to get the pointer of an object on the lua-stack, thought you need to cast your pointer back to your object class to call any methods of it.
But eventually it is really simple.

This topic is closed to new replies.

Advertisement