• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

使用lua扩展应用程序

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
  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\n",lua_tointeger(L,-1));
    lua_getglobal(L,"height");
    printf("height = %d\n",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\n");
    result = (int ) lua_tonumber(L,-1) * MAX_COLOR;
    lua_pop(L,1);  
    return result;
}

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
quick-cocos-2dx学习之【init.lua】发布时间:2022-07-22
下一篇:
Lua字符串替换函数string.gsub发布时间:2022-07-22
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap