Sign in to follow this  

Lua(jit) userdata metatable lost ?

This topic is 741 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I wrote this in lua:
body1 = physics.newbody("dynamic", 500, 100, 0)
body1:applyforce(10000, 0)
node2 = graphics.new_physnode(node1, body1, "phys1")
body1:applyforce(10000, 0)
the first time I called applyforce, it worked well. But at the second time, it became a nil value. So maybe it's the new_physnode that mess things up? this is new_physnode:
int l_new_physnode(lua_State* L) {
	ShapeNode* shapenode = (ShapeNode*)lua_touserdata(L, 1);
	Physics::hdbody body = (Physics::hdbody)lua_touserdata(L, 2);
	string name = lua_tostring(L, 3);
	PhysNode* physnode = graphics.new_physnode(shapenode, body, name);
	lua_pushlightuserdata(L, physnode);
	luaL_getmetatable(L, "Lua.Node");
	lua_setmetatable(L, -2);
	return 1;
}
it will just copy the pointer of body and shapenode then store them in physnode. yet I cannot get it to work. Why this is happening?(body's metatable becomes null but node's metatable remain the same...) thanks!

Share this post


Link to post
Share on other sites


Physics::hdbody body = (Physics::hdbody)lua_touserdata(L, 2);

What's that "Physics::hdbody" ?

If that's not a pointer, then physnode gets linked to temporary object on stack. After you exit l_new_physnode, physnode will be operating on invalid memory.

 


lua_pushlightuserdata(L, physnode);

Note: light userdata has no individual metatables.

If you want metatables - use normal userdata.

Share this post


Link to post
Share on other sites
Physics::hdbody is a pointer...and light userdata has no metatables? Oh, I think that's the point! thanks very much!

Share this post


Link to post
Share on other sites
...userdata has to be a block of memory which means I'll have to put the node's memory in it. What if I just want the function to return a pointer with a metatable instead of allocate new memory?(I shall manage memory in c++)

Share this post


Link to post
Share on other sites

You need to use a normal userdata so you must allocate it from LUA. If you want to manage your node's memory in C++ instead, you can allocate a userdata with the size of a pointer and store the pointer to the node in it. You'll have a double redirection but it will do what you want.

Share this post


Link to post
Share on other sites
Sign in to follow this