一個(gè)項(xiàng)目用到了Lua,開發(fā)人員對(duì)Lua庫(kù)進(jìn)行了一層封裝,以利于使用。但從封裝來看,如果對(duì)Lua庫(kù)本身不了解的話,還是很難使用。我覺得好的封裝應(yīng)該是不用再詳細(xì)理解原來的庫(kù)/語(yǔ)言的情況下就能使用,這樣的封裝才有較大的價(jià)值。關(guān)于如何在C++中調(diào)用Lua函數(shù),我做了自己的封裝嘗試,很不完整,但思路應(yīng)該是對(duì)的。
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
// 這里需要一個(gè)模板函數(shù),能將at中的所有數(shù)據(jù)
// push到lua棧中,略掉

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

}
};
舉一個(gè)例子,使用的時(shí)候可以像下面這樣調(diào)用:
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));

暫時(shí)沒有時(shí)間對(duì)Lua庫(kù)進(jìn)行較完整的封裝,以后有時(shí)間在做吧。