Lua編程示例(五): C語言對(duì)Lua表的讀取和添加
更新時(shí)間:2015年07月09日 10:42:53 投稿:junjie
這篇文章主要介紹了Lua編程示例(五): C語言對(duì)Lua表的讀取和添加,本文直接給出代碼實(shí)例,需要的朋友可以參考下
#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; //默認(rèn)棧頂是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); //刪掉產(chǎn)生的查找結(jié)果 return res; } void setfield(lua_State *L,char *key,double value){ //默認(rèn)棧頂是table lua_pushstring(L,key); lua_pushnumber(L,value); lua_settable(L,-3); //將這一對(duì)鍵值設(shè)成元素 } struct mycolor{ char *name; unsigned char red,green,blue; }Color[]={ {"WIETH",1,1,1}, {"BLACK",0,0,0}, {"BLUE",0,0,1} }; //先創(chuàng)建一個(gè)空的棧,填入元素,用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 中就一行代碼:
復(fù)制代碼 代碼如下:
background = {r=1,g=0.5,b=0.7}
運(yùn)行輸出結(jié)果為:
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
相關(guān)文章
openresty中使用lua-nginx創(chuàng)建socket實(shí)例
這篇文章主要介紹了openresty中使用lua-nginx創(chuàng)建socket實(shí)例,本文直接給出代碼實(shí)例和運(yùn)行效果,需要的朋友可以參考下2015-04-04Lua中的__index和__newindex實(shí)例
這篇文章主要介紹了Lua中的__index和__newindex實(shí)例,本文講解了具有默認(rèn)值的table、記錄table的訪問、只讀的table等內(nèi)容,需要的朋友可以參考下2014-09-09vs2012 error c4996: This function or variable may be unsafe
這篇文章主要介紹了vs2012 error c4996: This function or variable may be unsafe,需要的朋友可以參考下2015-04-04Lua函數(shù)與字符串處理簡(jiǎn)明總結(jié)
這篇文章主要介紹了Lua函數(shù)與字符串處理簡(jiǎn)明總結(jié),本文總結(jié)了單一參數(shù)、多個(gè)參數(shù)、可變參數(shù)、函數(shù)返回值及字符串處理等內(nèi)容,需要的朋友可以參考下2014-10-10Lua協(xié)同程序(COROUTINE)運(yùn)行步驟分解
這篇文章主要介紹了Lua協(xié)同程序(COROUTINE)運(yùn)行步驟分解,本文著重分解協(xié)同程序的運(yùn)行步驟,需要的朋友可以參考下2015-01-01