What means 'do --code; end'

I READ

local SomeClass
do
	SomeClass = setmetatable({}, {
		__tostring = function()
			return "SomeClass"
		end,
	})
	SomeClass.__index = SomeClass
	function SomeClass.new(...)
		local self = setmetatable({}, SomeClass)
		self:constructor(...)
		return self
	end
	function SomeClass:constructor()
		self._someprivatemember = true
	end
end

WHAT DOES ‘do’ DO AND WHY WE USE IT/

1 Like

a do end block is just a way to define a new scope. Not really any use besides scoping.

local soup = "dinosaur shapes"
do
    local hello = "world"
    print(soup, hello) --// dinosaur shapes world
end

print(soup, hello) --// dinosaur shapes nil

You really don’t need to do that at all in your code.

local SomeClass

SomeClass = setmetatable({}, {
    __tostring = function()
        return "SomeClass"
    end,
})
SomeClass.__index = SomeClass
function SomeClass.new(...)
    local self = setmetatable({}, SomeClass)
    self:constructor(...)
    return self
end
function SomeClass:constructor()
    self._someprivatemember = true
end

Or better said:

local SomeClass = {}

SomeClass.__index = SomeClass

function SomeClass.new(...)
    local self = setmetatable({}, SomeClass)

    self:constructor(...)
    return self
end

function SomeClass:constructor()
    self._someprivatemember = true
end

function SomeClass:__tostring()
    return "SomeClass"
end
3 Likes

The above answer is correct. Adding on, you’ll usually see a “do end” to define a variable when its value is an open statement. Meaning, we have to do some logic to get it. For example:

local howBlue do
    if Part.BrickColor == BrickColor.new("Light blue") then
        howBlue = "a little"
    elseif Part.BrickColor == BrickColor.new("Bright blue") then
        howBlue = "mostly"
    elseif Part.BrickColor == BrickColor.new("Really blue") then
        howBlue = "very"
    else
        howBlue = "none"
    end
end

It’s a silly example but I hope it illustrates my point. You don’t need to put it in the “do end” but doing that lets you collapse the block of code in the code editor.

2 Likes

Another use-case for this.

1 Like