使用lua扩展应用程序

  1. 全局变量的操作

void lua_getglobal(lua_State * L ,const char * name)

此函数从lua中取出一个名为name的全局变量并将其压入栈中。

如当lua文件内容为

width = 200
height = 300

时,以下代码

int _tmain(int argc, _TCHAR* argv[])
{

    lua_State *L = luaL_newstate();
    luaL_openlibs(L);


    if(0 != luaL_loadfile(L,"config_width_height.lua"))
    {
        printf("loadbuff error :%s",lua_tostring(L,-1));
        lua_pop(L,-1);
    }
    if(0 != lua_pcall(L,0,0,0))
    {
        printf("pcall error :%s",lua_tostring(L,-1));
        lua_pop(L,-1);
    }

    lua_getglobal(L,"width");
    printf("width  = %d
",lua_tointeger(L,-1));
    lua_getglobal(L,"height");
    printf("height = %d
",lua_tointeger(L,-1));


    lua_settop(L,0);
    lua_close(L);

    system("pause");
    return 0;
}

运行结果为
width  = 200
height = 300
请按任意键继续. . .

2.   table的操作

文件内容:

width = 200
height = 300

background =
{
    r = 0,
    g = 0,
    b = 1
}

获取以上 r g b的代码

    int red;
    int blue;
    int green;
    lua_getglobal(L,"background");   //push table
    if(lua_istable(L,-1))
    {
        red = getfield(L,"r");
        green = getfield(L,"g");
        blue = getfield(L,"b");
        printf("red:%d,green:%d blue:%d ",red,green,blue);
    }

注意:getfield不是 lua内置函数。getfield函数如下。

/*假设table 们位于栈顶*/
int getfield(lua_State * L,const char * key)
{
    int result ;
    lua_pushstring(L,key);      //push index
    lua_gettable(L,-2);//获取table   //pop index push table[index]
    if(!lua_isnumber(L,-1))
        printf("error is the value is not a value
");
    result = (int ) lua_tonumber(L,-1) * MAX_COLOR;
    lua_pop(L,1);  
    return result;
}
原文地址:https://www.cnblogs.com/zhangdongsheng/p/3176282.html