I'm currently programming a proof of concept text editor for computerCraft, in Lua; one feature will be line counting. How would one count the lines in a string, or at least count the newline characters? There would also ideally be line numbers at the side of the display/terminal, which may work with the same code.
I couldn't find any good enough search results, would appreciate a link if it's been answered already.
I've no idea how to do this, the ideal results would be an array with all the lines of text separated into different entries; this would answer both problems; but more 'bespoke' options may be present
Hopefully with help I can achieve an output like this...
1 |while true do
2 |sleep(0)
3 |write("Example")
4 |write("Script\n\n")
5 |end
:
PPPe Code Editor ~ 5 lines
...refreshing when something changes
You can use string.gsub
, as it returns the number of performed substitutions as the second result:
local _, replacements = string.gsub(text, "\n", "\n")
Update (4/22/19): If you need to add a line number to each line (the original question was about line counting), then you can still use string.gsub
, but you'll need to provide a function that will count the lines, for example:
lines = 1
local text = "1 |"..string.gsub(text, "\n", function(s) lines = lines + 1 return s..lines.." |" end)
print(text)
print(lines)
For your text, this will print:
1 |while true do
2 |sleep(0)
3 |write("Example")
4 |write("Script\n\n")
5 |end
5