Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I get the number of lines from a script source?

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:

function getLines()
	local count=0
	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}
	for subject=1,#objectsInGame do
		
		for _,v in pairs(objectsInGame[subject]:GetChildren()) do
			if v:IsA("Script") or v:IsA("LocalScript") or v:IsA("ModuleScript") then
				print("Was a script")
				local source=v.Source
				--add to line count
			end
		end
	end
	return count
end

There are no errors, all of it works fully.

1 answer

✓ Accepted answer

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.

local totalLength = #source

local sourceWithoutNewlines = source:gsub("\n", "")
-- Global substitution of newline with nothing

local lengthWithoutNewlines = #sourceWithoutNewlines

local numberOfNewlines = totalLength - lengthWithoutNewlines

local lineCount = numberOfNewLines + 1
-- 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:

local sourceWithoutNewlines, numberOfNewlines = source:gsub("\n", "")
local lineCount = numberOfNewlines + 1

1 comment

0

Cool, that's exactly what I needed! Thanks a lot!

This discussion is preserved as it was. New answers, comments, and votes are closed.