lua_settable、lua_gettable

函数原型:lua_gettable(lua_state * L, int index )

一句话____获取到index在栈上所对应的 table 的 key位置上的值  即t[key]

//从全局变量中获取一个table并且放到栈上-----现在table在index=-1的位置上
lua_gettable(l,"first_table");
//将要查找key压入栈上
lua_pushstring(l,"first_key");
//获取到指定index上的table的key位置上的值
lua_gettable(l,-2)

//打印结果:table,hello

注意-lua_gettable获取到的key值是在top of the stack;       //即使key与table不连续入栈也是可以的

且gettable(l,-2)函数结束后,将会把t[key]对应的值入栈,且把key的值出栈,table继续在栈中保留   

//他们两个的先后关系没有详细研究

下面是lua_settable(lua_state * L, int index)

lua_newtable(l)//l指代newstate()后的环境栈,创建一个新的table,并入栈

lua_pushstring(l,"speaking")  //key值先入栈

lua_pushstring(l,"table,hello") //value值入栈

lua_settable(l,-3)   //在table中设置key-value对,与gettable相对的,也要出栈,不过是pop两个值

lua_setglobal(l,"first_table")  //将table出栈,保存在全局变量中且变量名字为first_table
//全局变量环境其实就是一个表


还要一种设置table的方法

lua_newtable(sta);

lua_pushstring(sta,"table,hello")

lua_setfield(sta,-2,"speaking")

//set the table in the position of index,   set  t.speaking="table,hello"
then pop the top value of the stack
发布了12 篇原创文章 · 获赞 1 · 访问量 1274

猜你喜欢

转载自blog.csdn.net/qq_34250367/article/details/85054734
LUA