一个项目用到了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栈中弹出所有
  // 的参数, 然后返回,略掉
  
  }
}; 
举一个例子,使用的时候可以像下面这样调用:
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库进行较完整的封装,以后有时间在做吧。