0

こんにちは、私は JavaScript でこの関数を持っています:

    function blur(data) {
    var trimdata = trim(data);
    var dataSplit = trimdata.split(" ");
    var lastWord = dataSplit.pop();
    var toBlur = dataSplit.join(" ");
 }

これは、"Hello my name is bob" などの文字列を取得し、toBlur = "Hello my name is" および lastWord = "bob" を返します。

これをLuaで書き直す方法はありますか?

4

1 に答える 1

3

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

したがって[ ][^ ]*$、最後の単語と前のスペースに一致する必要があります。したがって、その(.*)前のすべてを返します。

splitJavaScript をより直接的に翻訳するには、まず、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すぐにテーブルを提供するのではなく、代わりにすべての一致に対する反復子を提供します。したがって、それらを独自の一時テーブルに追加し、それを呼び出しますconcatwords[#words+1] = ...配列の末尾に要素を追加する Lua のイディオムです。

于 2013-04-13T23:06:51.777 に答える