Quote:Original post by madmaurice
and what about light user data?
Almost the same as a regular userdata, except you only pass Lua a pointer.
If you explain what you are trying to do then maybe we could make a suggestion. You hardly are trying to expose a 2 integer struct called "somedata" to Lua!
What I do for my game is have an array (std::vector actually) of objects I want to expose to Lua. I provide an interface for getting and setting the values. I use simple functions to do this. Example:
struct Example{ int a,b; };std::vector<Example> examples;int create( lua_State *L ){ Example example; data.b = lua_tointeger(L,-1); lua_pop(L,1); data.a = lua_tointeger(L,-1); lua_pop(L,1); examples.push_back(example); // return index lua_pushinteger(L,examples.size()-1); return 1;}// and a similar function for bint setA( lua_State *L ){ int a = lua_tointeger(L,-1); lua_pop(L,1); int index = lua_tointeger(L,-1); lua_pop(L,1); if( index >= 0 && index < examples.size() ) { examples[index].a = a; } else { // handle error } return 0;}int getA( lua_State *L ){ int index = lua_tointeger(L,-1); lua_pop(L,1); if( index >= 0 && index < examples.size() ) { lua_pushinteger(L,examples[index].a); return 1; } else { // handle error } return 0;}
Then I write a lua script like so(assuming all the above functions are in a namespace/table "example"):
Example = {}function Example.new(a,b) local e = {} setmetatable(e,{__index=Example}) e.index = example.create(a,b) return eendfunction Example.getA() return example.getA(self.index)endfunction Example.setA(a) example.setA(self.index,a)end
This may not be the best way, but it has advantages for me. Firstly, the data remains in a contiguous block in C++, so I can store objects by value in a vector, rather than messing around with pointers. Also, I prefer writing table manipulation code in lua. I could change the C++ functions to parse lua tables but I find that awkward to write.
Obviously I just wrote that example off the top of my head - it has neither been compiled nor tested. In addition, it lacks error handling.