图解lua和C——table传递参数过程

先写测试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

参考:Lua C api 中让人头痛的栈与table传递

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值