How to make seven segment displays (parts)

I haven’t seen anybody make a tutorial on how to make seven segment displays out of parts before. So in this tutorial I will show you the basic concept, working, and function of my seven segment display system.

Seven segment displays can be used to display alphanumerical information and generally more visually appealing than just a text label, here are some examples:

And here is what I will show you how to make today (a very bare-bones version, but it can be improved, you’ll see soon):

DISCLAIMER

I am not a very good scripter, as such have taken most of my knowledge/code from other scripters on Roblox, they will be credited in the credits section at the end of the post.

Code used in this tutorial may not be fully optimized (I really don’t know how to optimize things) and so large amounts of seven segment displays may lag your game.

This tutorial is very long, you can skip to the end of each section if you want to just get the scripts and dont really care about understanding it.

The models I attach to this tutorial are fully open source, feel free to use them however you want to whatever extent.

Now let’s get into it!

Modeling the individual digits

Now, we must model the individual digits of the display, these will come together into the full display and help us show numbers and letters.

For a seven segment display, the industry standard in real life is like this:

You can make a version without the decimal point if you want, but I strongly suggest you include it.

Now, the individual segments can be rectangles, elongated hexagons, cylinders, triangles, whatever you want, just name the parts according to the standard and group them into a model:

For the script to work you should make sure that the segments name matches up with the standard, or else characters will not display properly.

Setting up the model/proper structure

Now, you must group the individual segments of the digit you just made into a model, it should look like this:

After you are done, duplicate the model and shift it right for each digit you want to add, then group it into another model. It should look like this (depending on how many digits you want):

Now, going from LEFT to RIGHT, name it starting from 1. For example if you have 6 digits, the leftmost digit is 1 and the rightmost digit is 6. It should look like this:

You can add a black background now inside the model so it’s easier to see the numbers, and remember to anchor everything so it doesn’t fall apart.

Scripting the display

Now is the last and hardest step, scripting the gauge.
Firstly you must add a script into the model, inside the script we will begin to code.

To begin, we initialize the display variables and add configurations in. Personally all my displays have configs so they are modular and can be reused.

local Display = script.Parent
local ValueObject = Display:WaitForChild("ValueObject")

--==================================================
-- CONFIG
--==================================================

local Config = {

	LitColor = Color3.fromRGB(255,0,0),
	UnlitColor = Color3.fromRGB(40,0,0),

	LitMaterial = Enum.Material.Neon,
	UnlitMaterial = Enum.Material.SmoothPlastic,

	Alignment = "Right", -- Left, Center, Right

	MaxDecimals = 4,
	ZeroPad = false,
	NegativeSignAtFirstDigit = true,

	MinValue = -999999,
	MaxValue = 999999,

	UnderRangeText = "UNDER",
	OverRangeText = "OVER",

	UpdateRate = 0.2,
}

After that we have to define the character map. This will tell the code which segments to light up to display the character. This is the standard I will be using (with a few additions and adjustments):


--==================================================
-- CHARACTER MAP
--==================================================
--[[
Lookup table for characters
Follows this format:

	A
F		B
	G
E		C
	D		DP
	

Looks like this:
	
   ---	
|  		|
|  		|
   ---	
|  		|
|  		|
   ---		.
	
DP is the decimal point
--]]
local Characters = {

	[" "] = {},
	["-"] = {"G"},

	["0"] = {"A","B","C","D","E","F"},
	["1"] = {"B","C"},
	["2"] = {"A","B","D","E","G"},
	["3"] = {"A","B","C","D","G"},
	["4"] = {"B","C","F","G"},
	["5"] = {"A","C","D","F","G"},
	["6"] = {"A","C","D","E","F","G"},
	["7"] = {"A","B","C"},
	["8"] = {"A","B","C","D","E","F","G"},
	["9"] = {"A","B","C","D","F","G"},

	["A"] = {"A","B","C","E","F","G"},
	["B"] = {"C","D","E","F","G"},
	["C"] = {"A","D","E","F"},
	["D"] = {"B","C","D","E","G"},
	["E"] = {"A","D","E","F","G"},
	["F"] = {"A","E","F","G"},
	["G"] = {"A","C","D","E","F"},
	["H"] = {"B","C","E","F","G"},
	["I"] = {"B","C"},
	["J"] = {"B","C","D","E"},
	["L"] = {"D","E","F"},
	["M"] = {"A","C","E","G"},
	["N"] = {"C","E","G"},
	["O"] = {"A","B","C","D","E","F"},
	["P"] = {"A","B","E","F","G"},
	["Q"] = {"A","B","C","F","G"},
	["R"] = {"E","G"},
	["S"] = {"A","C","D","F","G"},
	["T"] = {"D","E","F","G"},
	["U"] = {"B","C","D","E","F"},
	["V"] = {"F", "B", "D"},
	["W"] = {"B","D","F", "G"},
	["Y"] = {"B","C","D","F","G"},
	["Z"] = {"A","B","D","E","G"},
}

Next, we put all the digit models into a table and get the total number of digits

--==================================================
-- DIGIT DISCOVERY
--==================================================

local Digits = {} --Stores all the digit models

for _, Child in ipairs(Display:GetChildren()) do 
--Loops through every child, every child should be a seven segment 
--digit following the standard format with decimal point, named from 1-... from left to right
	local Number = tonumber(Child.Name)

	if Number then
		Digits[Number] = Child --Assigns the physical digits to the digit table
	end
end

local DigitCount = #Digits --Gets total number of digits

We will define a couple of helper functions to control the segments, clear the display, etc.

--==================================================
-- SEGMENT CONTROL
--==================================================

--[[
Controls a single segment, in a digit model there are 8 segments including DP 
as stated in the format.

@params Segment: The segment to control, should be named A, B, C, D, E, F, G, DP
@params State: The state of the segment, true is on and false is off.

Example: SetSegment(A, true) will light segment A
]]
local function SetSegment(Segment, State)
	if State then
		Segment.Color = Config.LitColor
		Segment.Material = Config.LitMaterial
	else
		Segment.Color = Config.UnlitColor
		Segment.Material = Config.UnlitMaterial
	end

end

--[[
Turns every segment off
]]
local function ClearDisplay()

	for _, Digit in ipairs(Digits) do --Loop through all digits
		for _, Segment in ipairs(Digit:GetChildren()) do --Loop through all segments in digit
			SetSegment(Segment,false) --Turn segments off
		end
	end

end


--[[
Draws one character on one digit

@params DigitModel: The digit model to draw the character on
@params Character: The character to draw
@params Decimal: If the decimal point should be shown

Example: DrawCharacter(Digits[3],"5",true) draws 5. on 1 digit
]]
local function DrawCharacter(DigitModel, Character, Decimal)
	--Get segment list from character map
	local Map = Characters[string.upper(Character)] or {}

	for _, Segment in ipairs(DigitModel:GetChildren()) do

		local Enabled = false --Reset and turn off all segments

		for _, Name in ipairs(Map) do --If segment is in character map turn it on
			if Segment.Name == Name then
				Enabled = true
				break
			end
		end

		if Segment.Name == "DP" then --Turn on decimal point if needed
			Enabled = Decimal == true
		end

		SetSegment(Segment, Enabled) --Set segment using check from above loop

	end

end

Now, because the display has the ability to use the decimal points, we need to check the length of the numbers/text with decimal points in mind.

--==================================================
-- HELPERS
--==================================================

--Returns amount of digits with DP check, example: VisibleLength("123.1") returns 4, should be  string
local function VisibleLength(Text)
	return #Text - select(2, string.gsub(Text, "%.", ""))
end

After that, we align the text based on the configurations, calculating padding and either putting it on the left/right or splitting on both sides to center the text.

--==================================================
-- ALIGNMENT
--==================================================

--[[
Aligns text left center right based on configurations
]]
local function Align(Text)
	--Check if it needs special handling
	local ForceNegative =
		Config.NegativeSignAtFirstDigit
		and Text:sub(1,1) == "-"

	if ForceNegative then
		Text = Text:sub(2) --Temporarily removes - sign
	end

	local Length = VisibleLength(Text) --Gets the length of string

	if ForceNegative then
		Length += 1 --Add back the minus sign
	end

	if Length > DigitCount then
		return nil --Overflow protection
	end

	local Padding = DigitCount - Length --Get total padding 

	local Result

	if Config.Alignment == "Left" then

		Result = Text .. string.rep(" ", Padding) --Prints text first and then adds padding behind it

	elseif Config.Alignment == "Center" then

		local Left = math.floor(Padding / 2) --Split padding between left and right
		local Right = Padding - Left

		Result =
			string.rep(" ", Left) --Pad left
			.. Text --Text
			.. string.rep(" ", Right) --Pad right

	else

		Result =
			string.rep(" ", Padding) --Prints padding first then adds text
			.. Text

	end

	if ForceNegative then
		Result = "-" .. Result --Add back the minus sign
		Result = Result:sub(1, DigitCount) 
	end

	return Result

end

If the display is over it’s limit, e.g. trying to display 999999 for a 5 digit display, we have to display an over/under text to let the viewer know.

It will also try the number of decimal values that fits it inside the display, conforming to the max decimals as stated in the config.

For example: 943.3334 will be displayed as 943.33 as we only have 5 digits, remember that the decimal point does not count as a digit.

--==================================================
-- NUMBER FORMATTER
--==================================================

--[[
Converts numbers into display text
Example: FormatNumber(123.1) returns "123.1"
]]
local function FormatNumber(Value)

	if Value > Config.MaxValue then
		return Config.OverRangeText --Over max text
	end

	if Value < Config.MinValue then
		return Config.UnderRangeText --Under min text
	end

	local Negative = Value < 0 --Store negative sign (boolean)
	Value = math.abs(Value) --Absolute value

	for Decimals = Config.MaxDecimals, 0, -1 do --Try all decimal values from max to min until it fits

		local Text = string.format("%." .. Decimals .. "f", Value) 

		if Negative then
			Text = "-" .. Text
		end
		
		--Check if it fits, if it does return it and end the loop
		if VisibleLength(Text) <= DigitCount then
			return Text
		end

	end

	return Config.OverRangeText

end

Now comes the main display loop, where we will loop through the digits and print the characters according to the character map, with some other functionality:

--==================================================
-- DISPLAY RENDER
--==================================================

--Main rendering function
local function Render(Value)

	local Text

	--If value if a number format it into text, if value is text then print it directly
	if typeof(Value) == "number" then
		Text = FormatNumber(Value)
	else
		Text = tostring(Value)
	end

	local ForcedNegative = false

	if Config.NegativeSignAtFirstDigit
		and Text:sub(1,1) == "-" then --Force negative if config says so and number is negative

		ForcedNegative = true
		Text = Text:sub(2)
	end

	local AlignmentDigits = DigitCount

	if ForcedNegative then
		AlignmentDigits -= 1 --Reserve 1 digit for the - sign
	end

	local OriginalDigitCount = DigitCount
	DigitCount = AlignmentDigits
	
	--Align text
	Text = Align(Text)

	DigitCount = OriginalDigitCount

	if not Text then
		Text = Align(Config.OverRangeText) or Config.OverRangeText
	end

	ClearDisplay()
	
	local CharactersToDraw = {} --Store individual characters
	local DecimalFlags = {} --Store decimal flags

	--Split characters and decimal flags into tables
	for i = 1, #Text do

		local Char = Text:sub(i,i)

		if Char == "." then

			local LastIndex = #CharactersToDraw

			if LastIndex > 0 then
				DecimalFlags[LastIndex] = true
			end

		else

			table.insert(CharactersToDraw, Char)

		end

	end

	local StartDigit = 1

	--Draw minus sign first if forced negative
	if ForcedNegative then

		DrawCharacter(
			Digits[1],
			"-",
			false
		)

		StartDigit = 2
	end

	--Loop through digits and draw the characters according to character table and decimal flags table
	for Index, Character in ipairs(CharactersToDraw) do

		local Digit = Digits[Index + StartDigit - 1]

		if Digit then
			DrawCharacter(
				Digit,
				Character,
				DecimalFlags[Index]
			)
		end

	end

end

Due to my modular design philosophy, I will use object values to get the values, and so we have another function:

--==================================================
-- VALUE FORMATTER
--==================================================
--Read object value and formats it
local function FormatValue()

	local Object = ValueObject.Value

	if not Object then
		return " "
	end

	if Object:IsA("NumberValue") then

		local Value = Object.Value

		if Config.ZeroPad
			and Config.Alignment == "Right"
			and Value >= 0 then

			local Text = FormatNumber(Value)

			local EffectiveDigits = DigitCount

			if Config.NegativeSignAtFirstDigit and Value < 0 then
				EffectiveDigits -= 1
			end

			local Missing = EffectiveDigits - VisibleLength(Text)

			if Missing > 0 then
				Text = string.rep("0", Missing) .. Text
			end

			return Text
		end

		return Value

	end

	if Object:IsA("StringValue") then
		return Object.Value
	end

	return " "

end

The last step is to make a loop to constantly update the display:

--==================================================
-- MAIN LOOP
--==================================================

--Main rendering loop
while true do
	Render(FormatValue())
	task.wait(Config.UpdateRate)
end

And finally, you have the complete script:

--==================================================
-- SEVEN SEGMENT DISPLAY
--==================================================

local Display = script.Parent
local ValueObject = Display:WaitForChild("ValueObject")

--==================================================
-- CONFIG
--==================================================

local Config = {

	LitColor = Color3.fromRGB(255,0,0),
	UnlitColor = Color3.fromRGB(40,0,0),

	LitMaterial = Enum.Material.Neon,
	UnlitMaterial = Enum.Material.SmoothPlastic,

	Alignment = "Right", -- Left, Center, Right

	MaxDecimals = 4,
	ZeroPad = false,
	NegativeSignAtFirstDigit = true,

	MinValue = -999999,
	MaxValue = 999999,

	UnderRangeText = "UNDER",
	OverRangeText = "OVER",

	UpdateRate = 0.2,
}

--==================================================
-- CHARACTER MAP
--==================================================
--[[
Lookup table for characters
Follows this format:

	A
F		B
	G
E		C
	D		DP
	

Looks like this:
	
   ---	
|  		|
|  		|
   ---	
|  		|
|  		|
   ---		.
	
DP is the decimal point
--]]
local Characters = {

	[" "] = {},
	["-"] = {"G"},

	["0"] = {"A","B","C","D","E","F"},
	["1"] = {"B","C"},
	["2"] = {"A","B","D","E","G"},
	["3"] = {"A","B","C","D","G"},
	["4"] = {"B","C","F","G"},
	["5"] = {"A","C","D","F","G"},
	["6"] = {"A","C","D","E","F","G"},
	["7"] = {"A","B","C"},
	["8"] = {"A","B","C","D","E","F","G"},
	["9"] = {"A","B","C","D","F","G"},

	["A"] = {"A","B","C","E","F","G"},
	["B"] = {"C","D","E","F","G"},
	["C"] = {"A","D","E","F"},
	["D"] = {"B","C","D","E","G"},
	["E"] = {"A","D","E","F","G"},
	["F"] = {"A","E","F","G"},
	["G"] = {"A","C","D","E","F"},
	["H"] = {"B","C","E","F","G"},
	["I"] = {"B","C"},
	["J"] = {"B","C","D","E"},
	["L"] = {"D","E","F"},
	["M"] = {"A","C","E","G"},
	["N"] = {"C","E","G"},
	["O"] = {"A","B","C","D","E","F"},
	["P"] = {"A","B","E","F","G"},
	["Q"] = {"A","B","C","F","G"},
	["R"] = {"E","G"},
	["S"] = {"A","C","D","F","G"},
	["T"] = {"D","E","F","G"},
	["U"] = {"B","C","D","E","F"},
	["V"] = {"F", "B", "D"},
	["W"] = {"B","D","F", "G"},
	["Y"] = {"B","C","D","F","G"},
	["Z"] = {"A","B","D","E","G"},
}

--==================================================
-- DIGIT DISCOVERY
--==================================================

local Digits = {} --Stores all the digit models

for _, Child in ipairs(Display:GetChildren()) do 
--Loops through every child, every child should be a seven segment 
--digit following the standard format with decimal point, named from 1-... from left to right
	local Number = tonumber(Child.Name)

	if Number then
		Digits[Number] = Child --Assigns the physical digits to the digit table
	end
end

local DigitCount = #Digits --Gets total number of digits

--==================================================
-- SEGMENT CONTROL
--==================================================

--[[
Controls a single segment, in a digit model there are 8 segments including DP 
as stated in the format.

@params Segment: The segment to control, should be named A, B, C, D, E, F, G, DP
@params State: The state of the segment, true is on and false is off.

Example: SetSegment(A, true) will light segment A
]]
local function SetSegment(Segment, State)
	if State then
		Segment.Color = Config.LitColor
		Segment.Material = Config.LitMaterial
	else
		Segment.Color = Config.UnlitColor
		Segment.Material = Config.UnlitMaterial
	end

end

--[[
Turns every segment off
]]
local function ClearDisplay()

	for _, Digit in ipairs(Digits) do --Loop through all digits
		for _, Segment in ipairs(Digit:GetChildren()) do --Loop through all segments in digit
			SetSegment(Segment,false) --Turn segments off
		end
	end

end


--[[
Draws one character on one digit

@params DigitModel: The digit model to draw the character on
@params Character: The character to draw
@params Decimal: If the decimal point should be shown

Example: DrawCharacter(Digits[3],"5",true) draws 5. on 1 digit
]]
local function DrawCharacter(DigitModel, Character, Decimal)
	--Get segment list from character map
	local Map = Characters[string.upper(Character)] or {}

	for _, Segment in ipairs(DigitModel:GetChildren()) do

		local Enabled = false --Reset and turn off all segments

		for _, Name in ipairs(Map) do --If segment is in character map turn it on
			if Segment.Name == Name then
				Enabled = true
				break
			end
		end

		if Segment.Name == "DP" then --Turn on decimal point if needed
			Enabled = Decimal == true
		end

		SetSegment(Segment, Enabled) --Set segment using check from above loop

	end

end

--==================================================
-- HELPERS
--==================================================

--Returns amount of digits with DP check, example: VisibleLength("123.1") returns 4, should be  string
local function VisibleLength(Text)
	return #Text - select(2, string.gsub(Text, "%.", ""))
end

--==================================================
-- ALIGNMENT
--==================================================

--[[
Aligns text left center right based on configurations
]]
local function Align(Text)
	--Check if it needs special handling
	local ForceNegative =
		Config.NegativeSignAtFirstDigit
		and Text:sub(1,1) == "-"

	if ForceNegative then
		Text = Text:sub(2) --Temporarily removes - sign
	end

	local Length = VisibleLength(Text) --Gets the length of string

	if ForceNegative then
		Length += 1 --Add back the minus sign
	end

	if Length > DigitCount then
		return nil --Overflow protection
	end

	local Padding = DigitCount - Length --Get total padding 

	local Result

	if Config.Alignment == "Left" then

		Result = Text .. string.rep(" ", Padding) --Prints text first and then adds padding behind it

	elseif Config.Alignment == "Center" then

		local Left = math.floor(Padding / 2) --Split padding between left and right
		local Right = Padding - Left

		Result =
			string.rep(" ", Left) --Pad left
			.. Text --Text
			.. string.rep(" ", Right) --Pad right

	else

		Result =
			string.rep(" ", Padding) --Prints padding first then adds text
			.. Text

	end

	if ForceNegative then
		Result = "-" .. Result --Add back the minus sign
		Result = Result:sub(1, DigitCount) 
	end

	return Result

end

--==================================================
-- NUMBER FORMATTER
--==================================================

--[[
Converts numbers into display text
Example: FormatNumber(123.1) returns "123.1"
]]
local function FormatNumber(Value)

	if Value > Config.MaxValue then
		return Config.OverRangeText --Over max text
	end

	if Value < Config.MinValue then
		return Config.UnderRangeText --Under min text
	end

	local Negative = Value < 0 --Store negative sign (boolean)
	Value = math.abs(Value) --Absolute value

	for Decimals = Config.MaxDecimals, 0, -1 do --Try all decimal values from max to min until it fits

		local Text = string.format("%." .. Decimals .. "f", Value) 

		if Negative then
			Text = "-" .. Text
		end
		
		--Check if it fits, if it does return it and end the loop
		if VisibleLength(Text) <= DigitCount then
			return Text
		end

	end

	return Config.OverRangeText

end

--==================================================
-- DISPLAY RENDER
--==================================================

--Main rendering function
local function Render(Value)

	local Text

	--If value if a number format it into text, if value is text then print it directly
	if typeof(Value) == "number" then
		Text = FormatNumber(Value)
	else
		Text = tostring(Value)
	end

	local ForcedNegative = false

	if Config.NegativeSignAtFirstDigit
		and Text:sub(1,1) == "-" then --Force negative if config says so and number is negative

		ForcedNegative = true
		Text = Text:sub(2)
	end

	local AlignmentDigits = DigitCount

	if ForcedNegative then
		AlignmentDigits -= 1 --Reserve 1 digit for the - sign
	end

	local OriginalDigitCount = DigitCount
	DigitCount = AlignmentDigits
	
	--Align text
	Text = Align(Text)

	DigitCount = OriginalDigitCount

	if not Text then
		Text = Align(Config.OverRangeText) or Config.OverRangeText
	end

	ClearDisplay()
	
	local CharactersToDraw = {} --Store individual characters
	local DecimalFlags = {} --Store decimal flags

	--Split characters and decimal flags into tables
	for i = 1, #Text do

		local Char = Text:sub(i,i)

		if Char == "." then

			local LastIndex = #CharactersToDraw

			if LastIndex > 0 then
				DecimalFlags[LastIndex] = true
			end

		else

			table.insert(CharactersToDraw, Char)

		end

	end

	local StartDigit = 1

	--Draw minus sign first if forced negative
	if ForcedNegative then

		DrawCharacter(
			Digits[1],
			"-",
			false
		)

		StartDigit = 2
	end

	--Loop through digits and draw the characters according to character table and decimal flags table
	for Index, Character in ipairs(CharactersToDraw) do

		local Digit = Digits[Index + StartDigit - 1]

		if Digit then
			DrawCharacter(
				Digit,
				Character,
				DecimalFlags[Index]
			)
		end

	end

end

--==================================================
-- VALUE FORMATTER
--==================================================
--Read object value and formats it
local function FormatValue()

	local Object = ValueObject.Value

	if not Object then
		return " "
	end

	if Object:IsA("NumberValue") then

		local Value = Object.Value

		if Config.ZeroPad
			and Config.Alignment == "Right"
			and Value >= 0 then

			local Text = FormatNumber(Value)

			local EffectiveDigits = DigitCount

			if Config.NegativeSignAtFirstDigit and Value < 0 then
				EffectiveDigits -= 1
			end

			local Missing = EffectiveDigits - VisibleLength(Text)

			if Missing > 0 then
				Text = string.rep("0", Missing) .. Text
			end

			return Text
		end

		return Value

	end

	if Object:IsA("StringValue") then
		return Object.Value
	end

	return " "

end

--==================================================
-- MAIN LOOP
--==================================================

--Main rendering loop
while true do
	Render(FormatValue())
	task.wait(Config.UpdateRate)
end

Now you must add an object value and a number value. Make sure the object value is linked to the number value, the end product should look like this:

Anyways, if you want to add another digit all you have to do is duplicate the rightmost one, shift it over and rename it according to the format.

Testing out the display

Now let’s see the display in action!

More details

I think you could use this same concept for 14 segment displays or even more, just go in and tweak the character map.

This is not the only way to make a seven segment display, you can make one with the seven segment module here:

The module does not have decimal capability though, so keep that in mind.

You can touch up the modeling and make it a lot better, and the end result could look like this:

Credits

Various

You may download the improved display model here:
SevenSegmentDisplay.rbxm (19.4 KB)

Again, if you want to add another digit all you have to do is duplicate the rightmost one, shift it over and rename it appropriately.

Thank you for viewing my tutorial!
If you have any questions or suggestions, you can reply below.

I did not steal the code from existing games, everything here was reverse engineered from scratch.

This is the third or maybe fourth tutorial that I have made, as such it may not be up to standards.
If so, please tell me how I can improve!
3 Likes

Cool guide. The code is very clean (most if not all functions even has comments explain them!!)
Idk when I’ll use it cuz they are usually used more in electronics than in games but sure :laughing:

Anyways, for people who want to know more about 7-segment displays in general, here’s the Wikipedia page for it: Segment display - Wikipedia

There are also 8-segment displays, 9-segment displays and more, and the logic for these are similar to the 7-segment guide here: Assign specific segments to specific number / letter and set the segment colors and stuff.

2 Likes