Lua(jit) userdata metatable lost ?

Started by
3 comments, last by Daixiwen 8 years, 3 months ago
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!
Advertisement


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.

Physics::hdbody is a pointer...and light userdata has no metatables? Oh, I think that's the point! thanks very much!
...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++)

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.

Definition of a man-year: 730 people trying to finish the project before lunch

This topic is closed to new replies.

Advertisement