Lua编程示例(五): C语言对Lua表的读取和添加
程序员文章站
2022-03-07 10:40:06
#include "stdafx.h"
lua_state *l;
void load_lua(char *filename){
l=lual_...
#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.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