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

What does "do" do?

from following (copied) example:

do
local PlayerColours = { -- Edit the colors you want to add or replace below. Must be brick colors.
BrickColor.new("Alder"),
BrickColor.new("Light blue"),
BrickColor.new("Pastel green"),
BrickColor.new("Sand green"),
BrickColor.new("Medium red"),
BrickColor.new("Dusty rose"),
BrickColor.new("Pastel orange"),
BrickColor.new("Pastel yellow"),
}
local GetNameValue

function GetChatColour(Name)
return PlayerColours[GetNameValue(Name) + 1]
end

function GetNameValue(Name)
	local Length = #Name
	local Value = 0
	for Index = 1, Length do
		local CharacterValue = string.byte(string.sub(Name, Index, Index))
		if (Length - Index + 1) % 4 < 2 then
			Value = Value + CharacterValue
		else
			Value = Value - CharacterValue
		end
	end
return Value % 8
	end
end


return GetChatColour

What is the purpose of the "do" at the start of the code?

2 comments

0

Creates a new scope.

0

2 answers

✓ Accepted answer

do is used to create a new scope. A scope is used mainly for manipulating and declaring variables without effecting other variables further down the script. Anything involving functions, loops, if statements, etc. creates a new scope.

a = 1

do
	local a = 2
	print(a) --prints 2
end

print(a) --prints 1
	

Here is the output of the same thing without using scopes:

a = 1

local a = 2
print(a) --prints 2

print(a) --prints 2

variables declared locally in scopes do not effect variables of unrelated scopes. They do, however, effect variables of scopes nested within them.

a = 1

do 
	local a = 2
	do
		print(a) --prints 2
	end
end

print(a) --prints 1

The do creates a new scope e.g

do
	print("abcd")
end

do
	print("efgh")
end

It's usually used to section of pieces of your code I guess.

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