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
したがって[ ][^ ]*$
、最後の単語と前のスペースに一致する必要があります。したがって、その(.*)
前のすべてを返します。
split
JavaScript をより直接的に翻訳するには、まず、Lua には関数がないことに注意してください。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 のイディオムです。