How do I make a line counter to a textbox?

I’ve always wondered how people made line counters in gui like this in Lua

I wanna learn how it works so I can have the number of the line next to the guibox
I have no clue how to do it, so any help is appreciated!


Can you elaborate on your question a bit? Are you asking how to recreate the line numbers in a gui box? If so, I’d create a frame for each line and put a text box next to each frame, with the line number as the text.

If you want to make a line counter, the obvious things you’ll need are a multiline string and a way to read each line. Luckily, my earlier problem could help you out here. My use case was needing to read the content off each line of a string, you could salvage any useful code there to make a counter:

Alternatively, another post wanted to check for new lines in strings, so you could use the guidance I gave on that post as a starting point for further research into the topic:

You can get the number of lines in a string this way

 local String = 
       [[line 1
       new line2
       new line3]]
 local function countLines(str)
 local lines = 0
 for _ in str:gmatch("\n") do -- string.gmatch(str, "\n") has a pending optimization because it's called directly from the string library, ideally use that instead of method calls, I used a method call as an alternative
     lines = lines + 1
 return lines + 1 -- account for last line

 print(countLines(String)) --> 3

The TextBox’s Multiline property should be true, so that it’s a multiline string.

Edit: I forgot about string.gsub(), probably a cleaner solution

Or you know just

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

Since the second return of gsub is how many replacements it made. For instance if there is 5 newlines then gsub will return 5.