Skip to content

Instantly share code, notes, and snippets.

@gaspard
Created January 15, 2012 07:42
Show Gist options
  • Save gaspard/1614891 to your computer and use it in GitHub Desktop.
Save gaspard/1614891 to your computer and use it in GitHub Desktop.
dub optimizations
// =========================================================== Return value optimization
/** Vect Vect::operator+(const Vect &v)
* test/fixtures/pointers/Vect.h:55
*/
static int Vect_operator_add(lua_State *L) {
try {
Vect *self = *((Vect**)dub_checksdata(L, 1, "Vect"));
Vect *v = *((Vect**)dub_checksdata(L, 2, "Vect"));
dub_pushudata(L, new Vect(self->operator+(*v)), "Vect");
return 1;
} catch (std::exception &e) {
lua_pushfstring(L, "operator+: %s", e.what());
} catch (...) {
lua_pushfstring(L, "operator+: Unknown exception");
}
return lua_error(L);
}
// =========================================================== No gc optimization
/** Nogc Nogc::operator+(const Nogc &v)
* test/fixtures/memory/Nogc.h:22
*/
static int Nogc_operator_add(lua_State *L) {
try {
Nogc *self = *((Nogc**)dub_checksdata(L, 1, "Nogc"));
Nogc *v = *((Nogc**)dub_checksdata(L, 2, "Nogc"));
dub_pushfulldata<Nogc>(L, self->operator+(*v), "Nogc");
return 1;
} catch (std::exception &e) {
lua_pushfstring(L, "operator+: %s", e.what());
} catch (...) {
lua_pushfstring(L, "operator+: Unknown exception");
}
return lua_error(L);
}
// =========================================================== dub_pushfulldata template
template<class T>
struct DubUserdata {
T *ptr;
T obj;
};
template<class T>
void dub_pushfulldata(lua_State *L, const T &obj, const char *type_name) {
DubUserdata<T> *copy = (DubUserdata<T>*)lua_newuserdata(L, sizeof(DubUserdata<T>));
copy->obj = obj;
// now **copy gives back the object.
copy->ptr = &copy->obj;
// the userdata is now on top of the stack
// set metatable (contains methods)
luaL_getmetatable(L, type_name);
lua_setmetatable(L, -2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment