你可以使用 Lua 的模式匹配工具:
function blur(data) do
return string.match(data, "^(.*)[ ][^ ]*$")
end
模式是如何工作的?
^ # start matching at the beginning of the string
( # open a capturing group ... what is matched inside will be returned
.* # as many arbitrary characters as possible
) # end of capturing group
[ ] # a single literal space (you could omit the square brackets, but I think
# they increase readability
[^ ] # match anything BUT literal spaces... as many as possible
$ # marks the end of the input string
所以[ ][^ ]*$
必须匹配最后一个单词和前面的空格。因此,(.*)
会返回它面前的一切。
为了更直接地翻译你的 JavaScript,首先要注意 Lua 中没有split
函数。虽然有table.concat
,它的工作原理类似于join
. 由于您必须手动进行拆分,您可能会再次使用模式:
function blur(data) do
local words = {}
for m in string.gmatch("[^ ]+") do
words[#words+1] = m
end
words[#words] = nil -- pops the last word
return table.concat(words, " ")
end
gmatch
不会立即为您提供表格,而是提供所有匹配项的迭代器。因此,您将它们添加到您自己的临时表中,然后调用concat
它。words[#words+1] = ...
是一个 Lua 习惯用法,用于将元素附加到数组的末尾。