luaworld-of-warcraft

How to remove last line from a string in Lua?


I am using Lua in World of Warcraft.

I have this string:

"This\nis\nmy\nlife."

So when printed, the output is this:

This
is
my
life.

How can I store the entire string except the last line in a new variable?

So I want the output of the new variable to be this:

This
is
my

I want the Lua code to find the last line (regardless of how many lines in the string), remove the last line and store the remaining lines in a new variable.

Thank you.


Solution

  • So I found that Egor Skriptunoff's solutions in the comments worked very well indeed but I am unable to mark his comments as an answer so I'll put his answers here.

    This removes the last line and stores the remaining lines in a new variable:

    new_str = old_str:gsub("\n[^\n]*$", "")
    

    If there is a new line marker at the end of the last line, Egor posted this as a solution:

    new_str = old_str:gsub("\n[^\n]*(\n?)$", "%1")
    

    While this removes the first line and stores the remaining lines in a new variable:

    first_line = old_str:match("[^\n]*")
    

    Thanks for your help, Egor.