Lua C/C++ Interface Quick View

风行水上 @ 2014-06-10 10:27:54
标签:

    Lua是一种脚本语言,多用于C/C++程序的扩展。

    下面是Lua和C/C++交互的基本用法。

    创建Lua解释器 & 创建函数

    /* Create a new function for Lua */
    
    static int myfunc(lua_State *L){
      int n = lua_gettop(L);
       lua_Number arg_1 = lua_tonumber(L, 1);
      lua_Number arg_n = lua_tonumber(L, n);
      lua_pushnumber(L, arg_1 + arg_n);
      lua_pushnumber(L, arg_1 - arg_n);
      return 2;
    }
    
    lua_State *L = luaL_newstate();  // Create Lua Intepreter
    
    lua_pushcfunction(L, myfunc);
    lua_setglobal(L, "myfunc");      /* register this function */
    
    lua_close(L);                    // Destroy Lua Intepreter
    

    如果要同时注册多个函数,可以借助luaL_setfuncs

    /* Register multiple functions */
    
    luaL_Reg func_list[1] = {
      {"myfunc", myfunc}
    };
    luaL_setfuncs(L, func_list, 0);
    

    luaL_newstate 的实现

    static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
      (void)ud;  (void)osize;  /* not used */
    
      if (nsize == 0) {
        free(ptr);
        return NULL;
      } else {
        return realloc(ptr, nsize);
      }
    }
    
    lua_State *L = lua_newstate(l_alloc, NULL)
    

    错误处理

    Lua的错误处理实质上是通过lua_atpanic注册一个函数(和普通的函数扩展没有质的不同)。

    static int panicf(lua_State *L){
      ... 
      return 0;
    }
    
    lua_atpanic(L, panicf);  // 注册错误处理函数
    

    在C中调用Lua函数

    如要要在C中调用一个Lua函数,就需要构建一个用于函数调用的Stack:

    /* Example:  v1, v2 = myfunc(13, 7) */
    
    lua_getglobal(L, "myfunc");    // push 函数
    lua_pushinteger(L, 13);        // push 参数
    lua_pushinteger(L, 7);         // push 参数
    lua_call(L, 2, 2);             // 调用函数,pop 所有参数及函数,push 结果
    
    lua_setglobal(L, "v2");        // pop 结果,赋值给变量
    lua_setglobal(L, "v1");        // pop 结果,赋值给变量
    

    关键是Stack

    Lua和C进行交互的关键是一个虚拟栈("virtual stack")。

    TODO ...

    标签:

      分享到:
      comments powered by Disqus

      27/31ms