c++创建lua table

https://blog.csdn.net/zhang197093/article/details/76758340

	lua_newtable(L);
	lua_pushstring(L, "name");
	lua_pushstring(L, "xiaoming222");
	lua_settable(L, -3);

1、
lua_newtable(L);
创建一个table,并且压入栈
结果:lua_newtable压栈1个

2、
lua_pushstring(L, “name”);
lua_pushstring(L, “xiaoming222”);
key的值为name,value为xiaoming222
结果:lua_pushstring压栈1个

3、将key和value设置到table中去
lua_settable(L, -3); //由于压入了key和value,所以此时的table索引为-3
结果:lua_settable出栈两个

4、将新建的table,起一个名字,叫xxx
lua_setglobal(L, “xxx”);
结果:lua_setglobal出栈1个

5、
lua_newtable(L);
lua_pushstring(L, “meimei”);
lua_setfield(L, -2, “name”);
结果:lua_setfield出栈一个

参考:https://blog.csdn.net/zhang197093/article/details/76758340

6、清空栈
int count = lua_gettop(L); //获取栈里的所有元素个数
lua_pop(L, count); //pop掉count个元素,此时栈里为空

7、获取表的长度
int count = lua_rawlen(L, -1);
helloTable = {name=“xiaoming”, age=12}——获取不到这种表的长度,长度为0
helloTable2 = {“xiaoming”, “xxx”, “3333”}——可以获取表的长度,长度为3

8、
lua_rawgeti(L, -1, 2);
-1,table所在的位置索引
2,是获取table的第2个元素,注意lua中索引是从1开始的。
这句代码意思是,获取table的第二个元素,并且将获取的值压入栈中。
获取之后使用:
const char* str2 = lua_tostring(L, -1);
比如table的第2个元素为string,使用lua_tostring(L,-1)即可获取值。
然后使用:
lua_pop(L,1)即可弹出栈顶的值。

9、
lua_getglobal(L, “helloTable2”);
int len = lua_rawlen(L, -1);

lua_pushstring(L, “xxa”);
lua_rawseti(L, -2, 4); //将栈顶元素xxa,设置到table中的4号位置,注意lua中的索引从1开始。设置之后,xxa出栈。
len = lua_rawlen(L, -1);

10、
表里套表
例如:
helloTable= {
{111, 222},
{333, 444},
{555, 666}
}
可以这样写:

	lua_State* L = luaL_newstate();
	/* 载入Lua基本库 */
	luaL_openlibs(L);
		
	//{111,222}
	lua_newtable(L);
	int count = lua_gettop(L);

	lua_newtable(L);
	count = lua_gettop(L);

	lua_pushinteger(L, 112);
	lua_rawseti(L, -2, 1);
	lua_pushinteger(L, 222);
	lua_rawseti(L, -2, 2);

	lua_rawseti(L, -2, 1);
	count = lua_gettop(L);

	//{333,444}
	lua_newtable(L);
	count = lua_gettop(L);

	lua_pushinteger(L, 333);
	lua_rawseti(L, -2, 1);
	lua_pushinteger(L, 444);
	lua_rawseti(L, -2, 2);

	lua_rawseti(L, -2, 2);
	count = lua_gettop(L);

	//{555,666}
	lua_newtable(L);
	count = lua_gettop(L);

	lua_pushinteger(L, 555);
	lua_rawseti(L, -2, 1);
	lua_pushinteger(L, 666);
	lua_rawseti(L, -2, 2);

	lua_rawseti(L, -2, 3);
	count = lua_gettop(L);

	lua_setglobal(L, "xxxx");
	luaL_dofile(L, "hello.lua");

在这里插入图片描述

Guess you like

Origin blog.csdn.net/wodownload2/article/details/120674142