談談Lua的封裝
一個項目用到了Lua,開發人員對Lua庫進行了一層封裝,以利于使用。但從封裝來看,如果對Lua庫本身不了解的話,還是很難使用。我覺得好的封裝應該是不用再詳細理解原來的庫/語言的情況下就能使用,這樣的封裝才有較大的價值。關于如何在C++中調用Lua函數,我做了自己的封裝嘗試,很不完整,但思路應該是對的。template<class RetTuple, class ArgTuple>
struct lua_function
{
lua_function(lua_State * L, const char * f)
: L_(L), f_(f)
{
}
RetTuple operator()(const ArgTuple & at)
{
// step 1
lua_getglobal(L_, f);
// step 2
// 這里需要一個模板函數,能將at中的所有數據
// push到lua棧中,略掉

//step 3
lua_pcall(L_,
boost::tuples::length<ArgTuple>::value,
boost::tuples::length<RetTuple>::value,
0);
// step 4
// 這里需要一個模板函數,能從lua棧中彈出所有
// 的參數, 然后返回,略掉

}
};
舉一個例子,使用的時候可以像下面這樣調用:struct lua_function
{
lua_function(lua_State * L, const char * f)
: L_(L), f_(f)
{
}
RetTuple operator()(const ArgTuple & at)
{
// step 1
lua_getglobal(L_, f);
// step 2
// 這里需要一個模板函數,能將at中的所有數據
// push到lua棧中,略掉

//step 3
lua_pcall(L_,
boost::tuples::length<ArgTuple>::value,
boost::tuples::length<RetTuple>::value,
0);
// step 4
// 這里需要一個模板函數,能從lua棧中彈出所有
// 的參數, 然后返回,略掉

}
};
using namespace boost::tuples;

lua_State * L = lua_open();
luaL_dostring(L, "function foo(a) return a*2.0 end")

lua_function<tuple<double, double>, tuple<double> > f(L, "foo");
tuple<double,double> ret = f(tuple<double>(3.5));

暫時沒有時間對Lua庫進行較完整的封裝,以后有時間在做吧。
lua_State * L = lua_open();
luaL_dostring(L, "function foo(a) return a*2.0 end")

lua_function<tuple<double, double>, tuple<double> > f(L, "foo");
tuple<double,double> ret = f(tuple<double>(3.5));

posted on 2008-03-05 23:10 long.muyi 閱讀(2005) 評論(2) 編輯 收藏 引用 所屬分類: Design