Consider the following:
class Vector3 {
public:
f64 x, y, z;
};
// pass an unkown userdata type to lua
template<typename T> inline void luaPushArg(lua_State * const LuaState, T arg) {
tolua_pushusertype(LuaState, (void*)&arg, typeid(T).name() + 6);
}
void testFunction(const Vector3 &v) {
luaPushArg(LuaState, v);
luaCallFunction("TestFunction"); // CRASH (only sometimes though!)
luaPop();
}
What went wrong here? Can you spot the bug? This one was a real pain in the tush. luaPushArg() would work with all my specialized types (int, float, etc) that I was passing to Lua, but when I passed classes it would sometimes crash. Turns out that luaPushArg() is taking a T arg instead of a T &arg. This means that a new copy of 'v' is created inside testFunction() when it calls luaPushArg(). luaPushArg() then pushes the newly created object onto the Lua stack. Upon luaPushArg()'s return, the pointer too the class object that was just pushed onto the lua stack is now invalidated. Sometimes it would crash, sometimes it wouldn't. This one was a real nightmare.
Hehehe . I can't wait for C11 support in GCC, that way bugs like this can be avoided using type-generic expression macros.