Whats the purpose of # in scripts?

I have noticed some scripts use “#” to make certain things happen, what exactly are they for?

‘#’ Gets the number of items in an array.

local array = {

1,  
2, 
3
 
}

print(#array) -- 3

local objects = {

workspace.Baseplate

}

print(#objects) -- 1
1 Like

“#” gets amount of items

Example:

colors = {
"Black",
"White",
"Red",
"Green",
"Blue"
}
print(#colors) --will print amount of colors 5
4 Likes

The unary operator (#) is used for the purpose of counting the number of elements (basically numeric indexes to the extent the table could be referred to as an array) within a table (same functionality table.getn(t)) - or the number of characters within a string.

The behavior is undefined when using it on tables with holes e.g nil, and using it on mixed tables returns the amount of incremental integral numeric indexes ignoring any non-numeric indexes in between.

local t = {1, 2, ind = "v", [3] = 3, i = "v"}
#t --> 3
local t = {1, 2, ind = "v", [4] = 3, i = "v"}
#t --> 2
-- with string literal
print(# "string") --> 6 (characters)

You can even use userdata for # to work with dictionaries or mixed tables
using the __len metamethod - as long as they don’t contain any holes.

local function wrap(t)
	local u = newproxy(true)
	local mt = getmetatable(u)
	setmetatable(mt, {__call = function() return t end});
	
	function mt.__len()
		local n = 0
		for _ in pairs(t) do
			n += 1
	  	end
		return n
	end
	
	return u
end

local t = {1,2,3, ind = "val"}
t = wrap(t)
print(getmetatable(t)(), -- to access the original table
	"\n",
	#t -- count
)
3 Likes