I'm developing a plugin that counts the lines in each and every script in a game, but I don't know how to detect a new line. Here's the main code so far:
01 | function getLines() |
02 | local count = 0 |
03 | local objectsInGame = { Workspace,game.Players,game.Lighting,game.ReplicatedFirst,game.ReplicatedStorage,game.ServerScriptService,game.ServerStorage,game.StarterGui,game.StarterPack,game.StarterPlayer,game.Soundscape,game.HttpService } |
04 | for subject = 1 ,#objectsInGame do |
05 |
06 | for _,v in pairs (objectsInGame [ subject ] :GetChildren()) do |
07 | if v:IsA( "Script" ) or v:IsA( "LocalScript" ) or v:IsA( "ModuleScript" ) then |
08 | print ( "Was a script" ) |
09 | local source = v.Source |
10 | --add to line count |
11 | end |
12 | end |
13 | end |
14 | return count |
15 | end |
There are no errors, all of it works fully.
There are a bunch of different ways to accomplish this.
source
is just a string, so we're somehow going to count newlines, which are specified by "\n"
(the newline character).
Intuitively, a really simple way is to remove all of the newlines and find out how much shorter the string got.
01 | local totalLength = #source |
02 |
03 | local sourceWithoutNewlines = source:gsub( "\n" , "" ) |
04 | -- Global substitution of newline with nothing |
05 |
06 | local lengthWithoutNewlines = #sourceWithoutNewlines |
07 |
08 | local numberOfNewlines = totalLength - lengthWithoutNewlines |
09 |
10 | local lineCount = numberOfNewLines + 1 |
11 | -- 1 line will have no \n so we add one |
In fact, gsub
will tell us how many things it substituted, so doing the length comparison is actually unnecessary:
1 | local sourceWithoutNewlines, numberOfNewlines = source:gsub( "\n" , "" ) |
2 | local lineCount = numberOfNewlines + 1 |