[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: binding a c++ unary_function to lua
- From: Vyacheslav Egorov <mraleph@...>
- Date: Mon, 07 Jan 2008 16:36:04 +0600
Panagiotis Vossos wrote:
Is there any easy way to make it available to lua as a normal function?
I think __call metamethod is what you are seeking.
Some untested and dirty (requires closure per functor and copy
constructor) code:
template<typename T>
int trampoline(lua_State *L) {
T *self = (T*)lua_touserdata(L, 1);
lua_remove(L, 1); // i am not sure that under normal circumstances
such removal is safe,
// i.e. f will not be GCed during execution,
// so I am doing a little trick with upvalues
return self->operator() (L);
}
template<typename T>
T *pushfunctor(lua_State *L, const T& f) {
T* p = (T*)lua_newuserdata(L, sizeof(T)); // stack: u ]
new (p) T(f);
lua_newtable(L); // stack: u t ]
lua_pushvalue(L, -2); // stack: u t u ]
lua_pushcclosure(L, &trampoline<T>, 1); // stack: u t f ]
lua_setfield(L, -2, "__call"); // stack: u t ]
lua_setmetatable(L, -2); // stack: u ]
return p;
}
--
e.v.e