luabind使用指南 – 入门篇

使用经验

  • 在Lua中调用C++函数时必须写上所有参数,包括缺省参数;
  • 在使用有 const char* 参数的注册函数中判断该参数是否为 NULL 的同时还要判断是否是空串,即"",并且在Lua中调用该函数时为 NULL 的参数改用空串""代替;
  • 不要在Lua中传递nil或0给字符串参数,在给Lua注册使用的函数接口中字符串参数尽可能的用std::string代替;
  • 有C++注册类对象的指针作为参数的注册函数,在Lua中调用时允许从nil转换到C++中的NULL;

 

在C++中调用Lua函数

 1 int main () {
 2   // 建立新的Lua环境 
 3   lua_State *L = luaL_newstate();
 4     
 5   // 让LuaBind“认识”这个Lua环境 
 6   luabind::open(L);
 7   
 8   // 定义一个叫add的Lua函数 
 9   luaL_dostring(L,
10     "function add(first, second)\n" 
11     "   return first + second\n" 
12     "end\n" 
13   );
14 
15   // 调用add函数
16   try {
17     std::cout << "Result: " 
18               << luabind::call_function<int>(L, "add"23)
19               << std::endl;
20 
21   } catch (luabind::error& e) {
22     std::cout << "Catch Exception: " << e.what() << std::endl;
23   }
24   
25   lua_close(L);
26     
27   return 0;
28 }

 

在Lua代码中调用C++函数

 1 void print_hello(int number) {
 2   std::cout << "hello world " << number << std::endl;
 3 }
 4 
 5 int main () {
 6   // 建立新的Lua环境 
 7   lua_State *L = luaL_newstate();
 8     
 9   // 让LuaBind“认识”这个Lua环境 
10   luabind::open(L);
11   
12   // 添加print_hello函数到Lua环境中 
13   luabind::module(L) [
14      luabind::def("print_hello", print_hello)
15   ];
16 
17   // 现在Lua中可以调用print_hello了
18   luaL_dostring(L, "print_hello(123)"); 
19 
20   lua_close(L); 
21     
22   return 0;
23 }

 

在Lua代码中使用C++类

 1 class NumberPrinter {
 2  public:
 3   NumberPrinter(int number) : m_number(number) {}
 4 
 5   void print() {
 6     std::cout << m_number << std::endl;
 7   }
 8 
 9  private:
10   int m_number;
11 };
12 
13 
14 int main () {
15   // 建立新的Lua环境 
16   lua_State *L = luaL_newstate();
17     
18   // 让LuaBind“认识”这个Lua环境 
19   luabind::open(L);
20   
21   // 使用LuaBind导出NumberPrinter类 
22   luabind::module(L) [
23     luabind::class_<NumberPrinter>("NumberPrinter")
24       .def(luabind::constructor<int>())
25       .def("print", &NumberPrinter::print)
26   ];
27 
28   // 现在Lua中可以使用NumberPinter类了 
29   luaL_dostring(L,
30     "Print2000 = NumberPrinter(2000) "
31     "Print2000:print() "
32   ); 
33 
34   lua_close(L);
35     
36   return 0;
37 }

 

 

参考资料

  1. Quick Introduction to LuaBind 
  2. 利用luabind将Lua嵌入到C++项目中
  3. Binding luabind::object to a boost::function

 

 

 

原文链接: https://www.cnblogs.com/edwardlost/archive/2011/11/12/2195688.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    luabind使用指南 - 入门篇

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/36268

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 下午1:02
下一篇 2023年2月8日 下午1:02

相关推荐