Sign in to follow this  
Roots

Making C++ containers accessible to Lua (Luabind)

Recommended Posts

Roots    1625
I've already got a solution in place to solve this particular problem, but I'm curious if others have come up with alternatives. I'm using Luabind for my C++/Lua binding, but I'd be interested to hear what people have using other binding solutions as well.


The problem is this. You have a container for a particular type that you want available to Lua. For example, lets say we want Lua to be able to access the contents of std::vector<int>, std::list<MyGameObject*>, and std::map<unsigned int, struct GameData>. What's the best way to make that data available to Lua?


Luabind doesn't support binding of template classes I believe, so its not like we could bind a std::vector or std::list template class to Lua and then be able to utilize vectors and lists with any data type we please. We'd have to bind the specific type of class instead (std::vector<int> for example) and do this for each class type we need access too, which may be a lot. Plus, we'd have to not only bind the classes but all the methods of that class we want available as well, such as size(), empty(), push_back(), etc. And I don't even want to think about binding iterators to Lua...:blink:


So the general solution I've been employing in my code is when I need access to a data container, I usually write two methods and bind them both to Lua. The first returns the element at a particular location. The second returns the size of the container. For example:

[code]
... (in class ResidentZone) ....

//! \brief A container that retains pointers to all sprites which occupy this zone
std::list<VirtualSprite*> _residents;

/** \brief Retrieves a pointer to a sprite that resides inside the zone
*** \param index The index of the resident sprite to retrieve
*** \return A pointer to the sprite, or NULL if there is no resident for the given index
***
*** \note This function is designed to allow Lua access to all sprite residents
**/
VirtualSprite* GetResident(uint32 index) const
{ return _GetSpriteInList(_residents, index); }

//! \brief Returns the number of sprites that are currently located within the zone boundaries
uint32 GetNumberResidents() const
{ return _residents.size(); }
[/code]


Then its up to the Lua code to use these two functions to iterate through every element in the container until it finds the data that its looking for, and act accordingly.



Is this typically how you solve this problem, or have you come up with a better/more clever/more efficient way? I'm curious to know. Thanks!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this