咔叽游戏

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 470|回复: 0

[Lua] Lua编程示例(五): C语言对Lua表的读取和添加

[复制链接]
  • TA的每日心情
    无聊
    2019-4-21 13:02
  • 签到天数: 3 天

    [LV.2]圆转纯熟

    发表于 2020-2-23 07:06:04 | 显示全部楼层 |阅读模式
    #include "stdafx.h"

    lua_State *L;


    void load_lua(char *filename){
    L=luaL_newstate();
    luaL_openlibs(L);
    if((luaL_loadfile(L,filename) || lua_pcall(L,0,0,0))!= 0){
    luaL_error(L,"loadfile error! \n %s",lua_tostring(L,-1));
    }
    }

    double getfield(lua_State *L,char * key){
    double res;
    //默认栈顶是table,将key入栈
    lua_pushstring(L,key);
    lua_gettable(L,-2);  //查找键值为key的元素,置于栈顶
    if(!lua_isnumber(L,-1)){
    luaL_error(L,"num get error! %s\n",lua_tostring(L,-1));
    }
    res = lua_tonumber(L,-1);
    lua_pop(L,1); //删掉产生的查找结果
    return res;
    }
    void setfield(lua_State *L,char *key,double value){
    //默认栈顶是table
    lua_pushstring(L,key);
    lua_pushnumber(L,value);
    lua_settable(L,-3); //将这一对键值设成元素
    }

    struct mycolor{
    char *name;
    unsigned char red,green,blue;
    }Color[]={
    {"WIETH",1,1,1},
    {"BLACK",0,0,0},
    {"BLUE",0,0,1}
    };
    //先创建一个空的栈,填入元素,用lua_setglobal弹出表,并赋成全局变量
    void setcolor(lua_State *L,struct mycolor col){
    lua_newtable(L);
    setfield(L,"r",col.red);
    setfield(L,"g",col.green);
    setfield(L,"b",col.blue);
    lua_setglobal(L,col.name);
    }

    void getcolor(lua_State *L,char *key){
    lua_getglobal(L,key);
    if(!lua_istable(L,-1)){
    luaL_error(L,"'background' is not a table! %s\n",lua_tostring(L,-1));
    }
    double red;
    double green;
    double blue;
    red = getfield(L,"r");
    blue = getfield(L,"b");
    green = getfield(L,"g");
    printf("The %s color : red = %.2f ,green = %.2f ,blue = %.2f\n",key,red,green,blue);
    }

    int _tmain(int argc, _TCHAR* argv[])
    {
    load_lua("test.lua");
    getcolor(L,"background");
    int i = 0;
    while(Color.name != NULL){
    setcolor(L,Color);
    i++;
    }
    getcolor(L,"WIETH");
    getcolor(L,"BLUE");
    return 0;
    }

    test.lua 中就一行代码:


    background = {r=1,g=0.5,b=0.7}  

    运行输出结果为:


    The background color : red = 1.00 ,green = 0.50 ,blue = 0.70
    The WIETH color : red = 1.00 ,green = 1.00 ,blue = 1.00
    The BLUE color : red = 0.00 ,green = 0.00 ,blue = 1.00

    QQ|免责声明|小黑屋|手机版|Archiver|咔叽游戏

    GMT+8, 2024-3-28 17:53

    Powered by Discuz! X3.4

    © 2001-2023 Discuz! Team.

    快速回复 返回顶部 返回列表