Search code examples
stringluacoronasdk

How to get lines count in string?


On the whole, I get a string from JSON pair which contain "\n" symbols. For example,

"I can see how the earth nurtures its grass,\nSeparating fine grains from lumpy earth,\nPiercing itself with its own remains\nEnduring the crawling insects on its surface.\nI can see how like a green wave\nIt lifts the soil, swelling it up,\nAnd how the roots penetrate the surrounding mulch\nHappily inhaling the air in the sky.\nI can see how the light illuminates the flowers, -\nPouring itself into their tight buds!\nThe earth and the grass – continue to grow!\nDrowning the mountains in a sea of green...\nOh, The power of motion of the young,\nThe muscular pull of the plants!\nOpening up to the planet, the sun and to you,\nBreaking through the undergrowth to the fresh spring air!"

This string is a poetry for some picture.

Now I need to resize my display.newText object according to text length.

Here is how I see to do that:

  1. Get number of lines (number of "\n" + 1, because where is no "\n" in the end)
  2. In for loop get the longest line
  3. Set display.newText object's size. May be using fontSize for calculating coefficient...

Question is: How to get number of lines?


Solution

  • To get the number of '\n' in a string, you can use string.gsub, it's used for string substitution, but it also returns the number of matches as the second return value.

    local count  = select(2, str:gsub('\n', '\n'))
    

    or similar:

    local _, count = str:gsub('\n', '\n')