国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > 綜合 > 正文

Lua編程示例(五): C語言對Lua表的讀取和添加

2024-07-21 23:04:59
字體:
來源:轉載
供稿:網友
#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[i].name != NULL){ setcolor(L,Color[i]); 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.70The WIETH color : red = 1.00 ,green = 1.00 ,blue = 1.00The BLUE color : red = 0.00 ,green = 0.00 ,blue = 1.00

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 四子王旗| 大丰市| 宿迁市| 抚顺市| 阿图什市| 和龙市| 泸西县| 朝阳市| 罗源县| 胶南市| 平潭县| 马公市| 巴里| 恭城| 宾川县| 汉寿县| 通榆县| 阿拉善右旗| 昆山市| 广南县| 泉州市| 五华县| 利津县| 茂名市| 天祝| 吉林省| 莱阳市| 德兴市| 松潘县| 称多县| 合水县| 灵武市| 大埔区| 绩溪县| 郴州市| 绥棱县| 遂宁市| 浠水县| 翁牛特旗| 中牟县| 桃园市|