Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Count the number of lines in a text box?

Asked by
CPF2 406 Moderation Voter
6 years ago

I looked for a way to do it, but couldn't find any ways.

is there a way to count the number of lines in a text box?

1 answer

Log in to vote
2
Answered by
Link150 1355 Badge of Merit Moderation Voter
6 years ago
local lines = #string.gsub(textBox.Text, '[^\n]+', '') + 1

What string.gsub does is it accepts a target string, a pattern string, and a replacement string, finds text in the target string that matches the pattern and then replaces it with the replacement string.

What my pattern [^\n]+ does is it matches sequences of "anything but newline characters '\n'". The function then replaces all these matches with the empty string, effectively leaving only newline characters in the string. The new string is then returned.

I then get the length of that result string, that gives me the amount of newline separators in the string to which I add 1 because, logically, there is one more line than there are separators.

Hope this helped. If you have any further questions feel free to comment. :)

Ad

Answer this question