Lua迭代器到数组 [英] Lua iterator to array
问题描述
用Lua的话来说,是否有任何语法糖可以将迭代器函数转换成数组(重复调用,结果存储在升序索引中),也许是标准库中的东西?
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.
代码(特定于我的用例)如下,我很难相信它不在标准库中:d
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
推荐答案
没有标准库函数.但实际上,编写起来很简单:
There's no standard library function for it. But really, it's pretty trivial to write:
function BuildArray(...)
local arr = {}
for v in ... do
arr[#arr + 1] = v
end
return arr
end
local myArr = BuildArray(<iterator function call>)
如果您的迭代器函数返回单个元素,这将仅 起作用.如果它返回多个元素,则必须做一些不同的事情.
This will only work if your iterator function returns single elements. If it returns multiple elements, you'd have to do something different.
这篇关于Lua迭代器到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!