• C++嵌入Lua读取配置文件


    这段时间一直在写工具,遇到一些问题,Google下解决了,这里想把解决问题的成果提取出来分享下,也方便我以后使用,^_^
    写工具就应该尽量的灵活,可配置性强,配置文件是少不了的。
    之前用过自定义配置文件(我的另一篇文章中提到过:http://www.cnblogs.com/MikeZhang/archive/2011/11/19/2255169.html),灵活是灵活,可写起来有点麻烦,而且如果想把部分逻辑写在外面,在配置文件中弄个函数就很不随意了——自己要写个脚本引擎进行解析……

    最后决定用lua作为配置文件的解析器,这里有个简单的demo:

     1 /*
    2 File : demo.cpp
    3 Author : Mike
    4 E-Mail : Mike_Zhang@live.com
    5 */
    6 #include <stdio.h>
    7 extern "C"
    8 {
    9 #include "lua.h"
    10 #include "lualib.h"
    11 #include "lauxlib.h"
    12 }
    13
    14 lua_State *L;
    15 const char *lua_Script = "function add(a, b) return (a+b) end ";
    16
    17 int lua_add(lua_State *L, const char *fun_name, int x, int y)
    18 {
    19 int ret;
    20 lua_getglobal(L, fun_name);
    21 lua_pushnumber(L, x);
    22 lua_pushnumber(L, y);
    23 lua_call(L, 2, 1);
    24 ret = (int)lua_tointeger(L, -1);
    25 lua_pop(L, 1);
    26 return ret;
    27 }
    28
    29 int test()
    30 {
    31 int ret = 0;
    32 lua_State *L = lua_open(); /* opens Lua */
    33 luaL_openlibs(L);
    34 if (luaL_dostring(L, lua_Script)) // Run lua script
    35 {
    36 printf("error!\n");
    37 lua_close(L);
    38 return -1;
    39 }
    40 ret = lua_add(L, "add", 4, 5);
    41 printf("%d\n",ret);
    42 lua_close(L);
    43 return 0;
    44 }
    45
    46 int main()
    47 {
    48 test();
    49 return 0;
    50 }

    另外,我自己写了个C++调用Lua的类,感兴趣的话,可以到这里去找:


    项目地址:http://sourceforge.net/projects/cppcalllua/
    svn访问:svn checkout http://svn.code.sf.net/p/cppcalllua/code-0/trunk cppcalllua-code-0

    Tips : 这是一个CodeBlocks的工程,工程文件 : CppCallLua.cbp


     

  • E-Mail : Mike_Zhang@live.com
  • 转载请注明出处,谢谢!
  • 相关阅读:
    App架构师实践指南四之性能优化一
    App架构师实践指南三之基础组件
    App架构师实践指南二之App开发工具
    App架构师实践指南一之App基础语法
    Linux下阅读MHT文件
    What Is Docker & Docker Container ? A Deep Dive Into Docker !
    Difference between Docker Image and Container?
    RabbitMQ .NET/C# Client API Guide
    How RabbitMQ Works and RabbitMQ Core Concepts
    Message Queue vs Message Bus — what are the differences?
  • 原文地址:https://www.cnblogs.com/MikeZhang/p/cppCallLua.html
  • Copyright © 2020-2023  润新知