Lua 迭代器到数组
用Lua的说法,是否有任何语法糖可以将迭代器函数转换为数组(重复调用,结果存储在升序索引中),也许是标准库中的东西?
我正在标记属于协议的字符串,并且需要对字符串开头的元素进行位置访问,而字符串的末尾是一个变体集合。
代码(特定于我的用例)如下,我很难相信它不在标准库中:d
local array_tokenise = function (line)
local i = 1;
local array = {};
for item in string.gmatch(line,"%w+") do
array[i] = item;
i = i +1
end
return array
end
In Lua parlance, is there any syntactic sugar for turning an iterator function into an array (repeated invocations with results stored in ascending indices), perhaps something in the standard library ?
I'm tokenizing a string belonging to a protocol and need to to have positional access to elements at the start of the string, and the end of the string is a variant collection.
The code (specific to my use-case) is as follows, I find it hard to believe that it isn't in the standard library :d
local array_tokenise = function (line)
local i = 1;
local array = {};
for item in string.gmatch(line,"%w+") do
array[i] = item;
i = i +1
end
return array
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有标准库函数。但实际上,编写起来非常简单:
只有当迭代器函数返回单个元素时,这才有效。如果它返回多个元素,您就必须做一些不同的事情。
There's no standard library function for it. But really, it's pretty trivial to write:
This will only work if your iterator function returns single elements. If it returns multiple elements, you'd have to do something different.
如果您只是想自动递增每个数据元素的表键,您可以使用 table.insert(collection, item) - 这会将项目追加到集合中并将键设置为集合计数 + 1
if you are just looking to auto-increment the table key for each data element, you can use table.insert(collection, item) - this will append the item to the collection and sets the key to the collection count + 1
正如 Nicol Bolas 所说,没有标准库函数可以执行您想要的操作。
下面是一个扩展
table
库的实用函数:下面是一些演示用法的示例代码:
输出:
stringify.lua
可以找到 此处As Nicol Bolas said, there is no standard library function that performs the action you desire.
Here is a utility function that extends the
table
library:Here is some example code demonstrating usage:
Output:
stringify.lua
can be found here