Tam2
Tam2

Reputation: 1367

Lua String Split

Hi I've got this function in JavaScript:

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

What this does is it take's a string such as "Hello my name is bob" and will return toBlur = "Hello my name is" and lastWord = "bob"

Is there a way i can re-write this in Lua?

Upvotes: 0

Views: 1221

Answers (1)

Martin Ender
Martin Ender

Reputation: 44259

You could use Lua's pattern matching facilities:

function blur(data) do
    return string.match(data, "^(.*)[ ][^ ]*$")
end

How does the pattern work?

^      # 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

So [ ][^ ]*$ has to match the last word and the preceding space. Therefore, (.*) will return everything in front of it.

For a more direct translation of your JavaScript, first note that there is no split function in Lua. There is table.concat though, which works like join. Since you have to do the splitting manually, you'll probably use a pattern again:

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 does not give you a table right away, but an iterator over all matches instead. So you add them to your own temporary table, and call concat on that. words[#words+1] = ... is a Lua idiom to append an element to the end of an array.

Upvotes: 3

Related Questions