lua_next(L,pos)
- 先从栈顶弹出一个key
- 从栈指定位置的table里取下一对key-value,先将key入栈再将value入栈
- 如果第2步成功则返回非0值,否则返回0,并且不向栈中压入任何值
- ps:L表示lua_State栈,pos表示位置
lua调用c++遍历key-value的table
//C++
int CTestTable(lua_State* L)
{
//先在栈底插入一个空的值
lua_pushnil(L);
while (lua_next(L, 1) != 0)
{
//push key, push value
printf("key = %s ", lua_tostring(L, -2));
printf(" value = %s \n", lua_tostring(L, -1));
lua_pop(L, 1);
}
return 0;
}
--lua
local tab = {name = "xiaoming",age="22",id="007"}
CTestTable(tab)
lua调用c++获取表中的一个key-value,不是整个表中的内容
- lua_getfield(l, 3, “name”)
int CTestTable(lua_State* L)
{
//只取表中的某个内容
lua_getfield(L, 1, "name");
printf("name = %s\n", lua_tostring(L, -1));
#if 0
//遍历表中的内容
//先在栈底插入一个空的值
lua_pushnil(L);
while (lua_next(L, 1) != 0)
{
//push key, push value
printf("key = %s ", lua_tostring(L, -2));
printf(" value = %s \n", lua_tostring(L, -1));
lua_pop(L, 1);
}
#endif
return 0;
}
Lua调用C++参数类型检查
luaL_checktype(l, 1, LUA_TBOOLEAN)
______ps:如果类型检测失败,程序不往下继续执行
ps: 下面这种方式,如果类型检测失败,程序还是可以继续往下执行的
- if(lua_type(l,1) != LUA_TBOOLEAN)
- {
- luaL_argerror(l,1,"bad argument");
- }
//C++
int CTestTable(lua_State* L)
{
//如果检测失败,不会继续往下执行了
//检查第一个参数的类型
luaL_checktype(L, 1, LUA_TTABLE);
//检查第二个参数的类型
if (lua_type(L, 2) != LUA_TNUMBER)
{
printf("para 2 is not a number\n");
}
//只取表中的某个内容
lua_getfield(L, 1, "name");
printf("name = %s\n", lua_tostring(L, -1));
#if 0
//遍历表中的内容
//先在栈底插入一个空的值
lua_pushnil(L);
while (lua_next(L, 1) != 0)
{
//push key, push value
printf("key = %s ", lua_tostring(L, -2));
printf(" value = %s \n", lua_tostring(L, -1));
lua_pop(L, 1);
}
#endif
return 0;
}
--lua
local tab = {name = "xiaoming",age="22",id="007"}
local num = s
CTestTable(tab, num)