Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Lua 我能从迭代器中得到最后一个值吗?_Lua - Fatal编程技术网

Lua 我能从迭代器中得到最后一个值吗?

Lua 我能从迭代器中得到最后一个值吗?,lua,Lua,我想用分隔符拆分字符串,只得到最后一部分。我 别在意其他的。我知道我能做到: local last for p in string.gmatch('file_name_test', '_%w+$') do last = p end 这很管用,但我觉得很难看 有没有更优雅的说法: local last = string.gmatch('file_name_test', '_%w+$')[1] 这不起作用,因为gmatch返回迭代器(而不是表)。使用string.match而不是迭代器: loc

我想用分隔符拆分字符串,只得到最后一部分。我 别在意其他的。我知道我能做到:

local last
for p in string.gmatch('file_name_test', '_%w+$') do last = p end
这很管用,但我觉得很难看

有没有更优雅的说法:

local last = string.gmatch('file_name_test', '_%w+$')[1]

这不起作用,因为
gmatch
返回迭代器(而不是表)。

使用
string.match
而不是迭代器:

local last = string.match('file_name_test', '_(%w+)$')
print (last)  --> test

模式
\u%w+$
将只返回一个匹配项。这是因为您将其锚定在字符串的末尾,因此它只能匹配或不匹配(如果末尾没有下划线后跟至少一个%w字符)

模式匹配的
g*
系列用于迭代匹配序列。如果希望一次返回所有匹配项(作为多个返回值返回),请使用非前缀函数。如
字符串。匹配

string.match('file_name_test', '_%w+$')

如果没有匹配项,那么您将返回
nil

尽管其他答案确实为您的情况提供了正确答案,但我将对您的问题提出一个答案。从迭代器中获取第一项

答案其实很简单。因为迭代器只是一个不断返回直到返回nil的东西,所以我们只需要调用它

local first = string.gmatch('file_name_test', '_%w+$')()

然而,我很困惑,因为在你的问题中,你还问了它最后会返回的东西。我很遗憾地说,如果不对它们全部进行迭代,您就无法做到这一点,因为迭代器不能“向前跳”。

Minor:因为u被认为是分隔符,所以它不应该是答案的一部分。因此,可能是这样的:local last=string.match('file_name_test',''u(%w+)$')这个问题在这一点上有点不清楚,因为原始代码也会返回下划线。然而,我修改了我的答案,使最后一个单词成为捕获,所以现在它只返回“test”。