[英]What is the C interface to Lua for accessing a table's key/value pairs?
In Lua, using the C interface, given a table, how do I iterate through the table's key/value pairs? 在Lua中,使用C接口,给定一个表,如何遍历表的键/值对?
Also, if some table table members are added using arrays, do I need a separate loop to iterate through those as well or is there a single way to iterate though those members at the same time as the key/value pairs? 另外,如果使用数组添加了一些表表成员,我是否需要一个单独的循环来迭代这些成员,或者是否有一种方法可以同时迭代这些成员作为键/值对?
As Javier says, you want the lua_next()
function. 正如Javier所说,你想要
lua_next()
函数。 I thought a code sample might help make things clearer since this can be a little tricky to use at first glance. 我认为代码示例可能有助于使事情更清晰,因为乍一看这可能有点棘手。
Quoting from the manual: 引自手册:
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); }
Be aware that lua_next()
is very sensitive to the key value left on the stack. 请注意,
lua_next()
对堆栈上剩余的键值非常敏感。 Do not call lua_tolstring()
on the key unless it really is already a string because that function will replace the value it converts. 不要在键上调用
lua_tolstring()
,除非它确实已经是一个字符串,因为该函数将替换它转换的值。
lua_next()
is just the same as Lua's next()
function, which is used by the pairs()
function. lua_next()
与Lua的next()
函数相同,后者由pairs()
函数使用。 It iterates all the members, both in the array part and the hash part. 它迭代数组部分和散列部分中的所有成员。
If you want the analogue of ipairs()
, the lua_objlen()
gives you the same functionality as #
. 如果你想要
ipairs()
的模拟, lua_objlen()
给你的功能与#
相同。 Use it and lua_rawgeti()
to numerically iterate over the array part. 使用它和
lua_rawgeti()
以数字方式迭代数组部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.