🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## lua_pop & lua_settop ### lua_settop 我们直接来看`lua_settop`,文档解释 ``` /* 设置栈的高度,如果之前的栈顶比新设置的更高,那么高出来的元素会被丢弃,反之压入nil来补足大小 假设栈里有2个元素。 如果index=0,那么移除栈上所有元素 如果index=1,移除栈顶一个元素 如果index=4,那么压入2个nil元素 */ void lua_settop (lua_State *L, int index); ``` 使用代码测试 ```c int lua_test(lua_State *L) { int pop_num = lua_tointeger(L,1); printf("pop_num= %d\n", pop_num); lua_settop(L,0); printf("1-top %d\r\n",lua_gettop(L)); lua_pushinteger(L,31); lua_pushinteger(L,32); lua_pushinteger(L,33); lua_pushinteger(L,34); printf("2-top %d\r\n",lua_gettop(L)); lua_pop(L,pop_num); lua_settop(L, -2); //清除一个栈顶 printf("3-top %d\r\n",lua_gettop(L)); printf("栈底 %d\r\n",lua_tointeger(L,1)); printf("栈顶 %d\r\n",lua_tointeger(L,-1)); return 0; } ``` 输出 ``` pop_num= 0 1-top 0 2-top 4 3-top 3 栈底 31 栈顶 33 ``` 总结`lua_settop(L, idx)`函数 * idx=0 栈中元素全部移除 * idx>0 设置栈的高度,如果之前的栈顶比新设置的更高,那么高出来的元素会被丢弃,反之压入nil来补足大小 * idx<0 idx=-1表示栈顶,栈不受影响;idx=-2表示清除一个栈顶元素,一次类推; ### lua_pop 从代码里看到 ``` #define lua_pop(L,n) lua_settop(L, -(n)-1) ``` 因为`lua_pop`是`lua_settop`宏定义, lua_pop(L,num)函数表示从栈顶开始移除。 * 当num>0时从栈顶移除指定个数 。 * 当num=0时栈不受影响 * 当num<0,当num=-1时栈中元素全部移除; num=-2表示清除一个栈顶元素,一次类推; * 但是负数编号不能超出栈底的负数索引,超出会抛出异常 ## bc ``` /** * 把给定索引处的 Lua 值转换为 lua_Integer 这样一个有符号整数类型 * 必须:数字/字符串类型数字 */ LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *pisnum) * idx = -1代表栈顶 * idx = 1 代表栈底 /** * 返回LUA 栈的个数 * 同时也是栈顶元素的索引,因为栈底是1 */ LUA_API int lua_gettop (lua_State *L) ``` 参考链接:http://www.daileinote.com/computer/lua/17