From 00d8215e00dedff240fa95f0a7719cd9d4370a25 Mon Sep 17 00:00:00 2001 From: Pavel Labath Date: Fri, 12 Feb 2010 17:41:24 +0100 Subject: [PATCH] added state::createuserdata template function --- src/luamm.cc | 6 ++---- src/luamm.hh | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/luamm.cc b/src/luamm.cc index ca73f4b5..bcc24652 100644 --- a/src/luamm.cc +++ b/src/luamm.cc @@ -94,10 +94,9 @@ namespace lua { catch(...) { // C++ exceptions (pointers to them, actually) are stored as lua userdata and // then thrown - void *ptr = L->newuserdata(sizeof(std::exception_ptr)); + L->createuserdata(std::current_exception()); L->rawgetfield(REGISTRYINDEX, cpp_exception_metatable); L->setmetatable(-2); - new(ptr) std::exception_ptr(std::current_exception()); } // lua_error does longjmp(), so destructors for objects in this function will not be @@ -386,10 +385,9 @@ namespace lua { { checkstack(2); - void *ptr = newuserdata(sizeof(cpp_function)); + createuserdata(fn); rawgetfield(REGISTRYINDEX, cpp_function_metatable); setmetatable(-2); - new(ptr) cpp_function(fn); insert(-n-1); lua_pushcclosure(cobj.get(), &closure_trampoline, n+1); diff --git a/src/luamm.hh b/src/luamm.hh index 20101073..3ad38ac8 100644 --- a/src/luamm.hh +++ b/src/luamm.hh @@ -263,6 +263,10 @@ namespace lua { // lua_tostring uses NULL to indicate conversion error, since there is no such thing as a // NULL std::string, we throw an exception. Returned value may contain '\0' std::string tostring(int index) throw(lua::not_string_error); + // allocate a new lua userdata of appropriate size, and create a object in it + // pushes the userdata on stack and returns the pointer + template + T* createuserdata(Args&&... args); }; /* @@ -291,6 +295,16 @@ namespace lua { void operator+=(int n_) throw() { n+=n_; } void operator-=(int n_) throw() { n-=n_; } }; + + template + T* state::createuserdata(Args&&... args) + { + stack_sentry s(*this); + + void *t = newuserdata(sizeof(T)); ++s; + new(t) T(std::forward(args)...); --s; + return static_cast(t); + } } #endif /* LUAMM_HH */