先写测试lua脚本:
local mytable = require("mytable")
local tb = {"hello", "world"}
local element = mytable.get(tb, 1)
这个mytable就是我们用C语言编译的库,给lua调用。
local element = mytable.get(tb, 1)
这个函数从lua向c传递了2个参数,第一个参数是一个table,另外一个数据是个整数,表示table的下标。
解释一下,栈顶和栈底没什么问题,现在是索引,负数的一列是负向索引;正数的一列是正数索引。
举例说明:
若有9个元素分别入栈,则:
1. 正数索引,栈底是1,然后一直到栈顶是逐渐+1,最后变成9(9大于1)
2. 负数索引,栈底是-9,然后一直到栈顶是逐渐+1,最后变成-1(-1大于-9)
正负索引的应用场景:
1. 正数索引,不需要知道栈的大小,我们就能知道栈底在哪,栈底的索引永远是1
2. 负数索引,不需要知道栈的大小,我们就能知道栈顶在哪,栈顶的索引永远是-1
参考:lua堆栈
main.c文件:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
static int l_get(lua_State *L)
{
luaL_checktype(L, 1, LUA_TTABLE);
size_t len = luaL_len(L, 1);
int pos = (int)luaL_checknumber(L, 2);
if (pos >= 1 && pos <= len)
{
//lua_geti(L, 1, pos);
//lua_rawgeti(L, 1, pos);
lua_pushnumber(L, pos);
lua_gettable(L, 1);
int count = lua_gettop(L);
printf("count = %d\n", count);
}
else
{
lua_pushnil(L);
}
return 1; //这是是返回个数
}
static luaL_Reg libs[] =
{
{"get", l_get},
{NULL, NULL}
};
__declspec(dllexport)//这个很重要,设置这个函数为外部链接 Linux不需要
int luaopen_mytable(lua_State* L) //函数名很重要
{
luaL_newlib(L, libs);
return 1;
}
这里是pos就是传递过来的table是索引
lua_pushnumber(L, pos); 执行完这句后:
栈成为这样:
lua_gettable(L, 1); 这句执行后变成了:
static int l_get(lua_State *L)
{
...
return 1;
}
这里的return 1;是返回个数,告诉调用这个函数的lua,我要返回几个值,你就从栈里依次取几个值(从栈顶开始取)
如图所示:
(1) 当return 1;时,
local element = mytable.get(tb, 1)
element 的值为hello
(2) 当return 2;时
local newtable, index, = mytable.get(tb, 1)
newtable = tb; index = 1;
(3) 当return 3;时,
local mytable = require("mytable")
local tb = {"hello", "world"}
local newtable, index, element = mytable.get(tb, 1)
print("newtable:", type(newtable), " index:",index,"element:",element)
这时候输出结果:
D:\lua_test>lua test_mytable.lua
count = 3
newtable: table index: 1 element: hello