c、c++提供接口供lua脚本调用时,会涉及到参数的调用,那么在c、c++层是如何遍历参数的呢?
static bool searchTable(lua_State* L, int idx)
{
lua_pushnil(L);
while (lua_next(L, idx) != 0)
{
//lua的table的key只可能是
int keyType = lua_type(L, -2);
if (LUA_TNUMBER == keyType)
{
if (lua_isinteger(L, -2)) std::cout << "key:" << lua_tointeger(L, -2) << '|';
else std::cout << "key:" << lua_tonumber(L, -2) << '|';
}
else if (LUA_TSTRING == keyType)
{
std::cout << "key:" << lua_tostring(L, -2) << '|';
}
else
{
std::cout << "invalid key type:" << lua_typename(L, keyType) << '\n';
return false;
}
int valueType = lua_type(L, -1);
switch (valueType)
{
case LUA_TNIL:printf("Value:nil\n"); break;
case LUA_TBOOLEAN:printf("Value:%s\n", lua_toboolean(L, -1) ? "true" : "false"); break;
case LUA_TNUMBER:
if (lua_isinteger(L, -1)) printf("Value:%lld\n", lua_tointeger(L, -1));
else printf("Value:%f\n", lua_tonumber(L, -1));
break;
case LUA_TSTRING:printf("Value:%s\n", lua_tostring(L, -1)); break;
case LUA_TTABLE:
{//找到是一个表,此时栈顶上是一个表,获取该表的位置索引
int index = lua_gettop(L);
searchTable(L, index);
}
break;
default:
{
printf("invalid value type:%s,\n", lua_typename(L, valueType));
return false;
}
}
lua_pop(L, 1);//删除栈顶1个元素,此时的栈顶是value,所以这个操作相当于删除了value,保留了key,至于为啥要这么做,看lua_next的解释
}
return true;
}
static int export_print(lua_State* L)
{
int n = lua_gettop(L); /* number of arguments */
//std::cout << "number of arguments is " << n << '\n';
int index = 1;
for (int index=1; index<=n; ++index)
{
int type = lua_type(L, index);
if (LUA_TNIL == type)
{
std::cout << "value is nil\n";
}
else if (LUA_TBOOLEAN == type)
{
std::cout << "value is boolean:" << (lua_toboolean(L, index) ? "true" : "false") << '\n';
}
else if (LUA_TNUMBER == type)
{
if (lua_isinteger(L, index)) std::cout<<"value is integer:"<<lua_tointeger(L, index) << '\n';
else std::cout<<"value is double:"<<lua_tonumber(L, index) << '\n';
}
else if (LUA_TSTRING == type)
{
std::cout << "value is string:" << lua_tostring(L, index) << '\n';
}
else if (LUA_TTABLE == type)
{
std::cout << "【value is table】\n";
searchTable(L, index);
}
else
{
std::cout << "value is other type:" << lua_typename(L, type) << '\n';
}
}
return 0;
}