gpt4 book ai didi

c - 用于访问表的键/值对的 Lua 的 C 接口(interface)是什么?

转载 作者:太空狗 更新时间:2023-10-29 15:45:40 25 4
gpt4 key购买 nike

在 Lua 中,使用 C 接口(interface),给定一个表,我如何遍历表的键/值对?

此外,如果使用数组添加一些表表成员,我是否也需要一个单独的循环来遍历这些表成员,或者是否有一种方法可以在键/值对的同时遍历这些成员?

最佳答案

正如 Javier 所说,您想要 lua_next()功能。我认为代码示例可能有助于使事情更清楚,因为乍一看这可能有点棘手。

引用手册:

A typical traversal looks like this:

/* table is in the stack at index 't' */
lua_pushnil(L); /* first key */
while (lua_next(L, t) != 0) {
/* uses 'key' (at index -2) and 'value' (at index -1) */
printf("%s - %s\n",
lua_typename(L, lua_type(L, -2)),
lua_typename(L, lua_type(L, -1)));
/* removes 'value'; keeps 'key' for next iteration */
lua_pop(L, 1);
}

请注意 lua_next() 对堆栈中剩余的键值非常敏感。 不要在键上调用lua_tolstring(),除非它确实已经是一个字符串,因为该函数将替换它转换的值。

关于c - 用于访问表的键/值对的 Lua 的 C 接口(interface)是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/966568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com