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

Can I have a complete explanation of #String?

I see it everywhere and know some examples of it being used, but I don't have a complete understanding of it. I've tried looking online for a bit but found nothing.

local strings = {"Hello", "World!"}
local ARandomStringThing = strings[math.Random(1, #Strings)] -- Uses #String
print(ARandomStringThing) -- Would print Hello or World
--Random String Picker

This piece of code above uses #string on line 2.

function findPlayer(r)
	for i, v in pairs(game.Players:GetPlayers()) do
		local n = v.Name:lower()
		if r == n:sub(1, #r)  then -- #string
			return v
		end
	end
end

This other example above is a part in my admin script, which is a function which finds a player even if you don't type the full name and uses #string. So again, what does #string mean?

1 answer

✓ Accepted answer

The # operator is called the length operator. It is used to find the number of letters in a string, or the number of items in a table.

local a = {2, 3 ,4} --table
print(#a) --prints 3, since a has 3 items inside of it.

local b = "hello"
print(#b) -- prints 5, since 'hello' has 5 letters.

Your first code example uses the length of the table to get a random item from the strings table. Instead of manually inputting the number of items of strings inside the table, we can just use the length operator on the table to get the number of items inside it. This way, if you want to expand the table, you do not have to change the range of math.random manually.

Your second piece of code uses the length operator on the input string r. It is used to check if the player's name truncated to the length of r is equal to the input string r. If it is equal, we found our player.

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