基于Lua实现C和C++程序的动态配置

  
       .Net程序可轻易的实现动态配置,我一直都想为我的C++服务程序也实现运行时可动态更改的配置,直到接触了Lua之后才发现原来是如此的简单。

       Lua是可嵌入到CC++程序的脚本语言,其强大的应用在网络游戏《魔兽争霸》中得到了淋漓尽致的体现。作为一个初学者,这里我只讨论怎样基于Lua实现运行时可动态更改的配置。

       原来的配置是ini格式的,例如:

       [contact]
       name = "zhangtao"
       email = "hack@ogdev.net"   
       url   = "http://www.ogdev.net"
      
age = 20

        改为Lua文件,是如下格式:
        contact ={
              name = "zhangtao",
              email = "hack@ogdev.net",
              url   = "http://www.ogdev.net",
              quote = [[There are 10 types of people
                      who can understand binary.]], --Lua支持的多行字符串
              age = 20,
              rate = 30.22 --Lua支持的浮点数
        }

        在LuaPlus库的基础上,我写了个类LuaConfigReader,这样读取配置内容就变得如此简单:
      const char * section = "contact";
      std::string file = "config.lua";

      LuaConfigReader reader(file);

      printf(" name = %s\n",reader.getString(section,"name"));
      printf(" quote = %s\n",reader.getString(section,"quote"));
      printf(" age = %d\n",reader.getInteger(section,"age"));     

        这样,程序的配置可扩展性就很好了。而且,在程序运行中可随时更改配置内容,一旦配置保存将立刻生效。这只是Lua最最基本的用处,算是一个敲门砖吧。

      备注:Lua只提供C接口,LuaPlus LuaC++封装。

posted @ 2006-07-15 17:33  观无明  阅读(1982)  评论(2编辑  收藏  举报