I'm well aware of the idea of scoping, and how lexical scoping works in general. I've heard that the idea of a do ... end
block is to limit the scope of certain variables, but what's the point? When would this ever be necessary or even practical? It seems to me that the usage of local variables makes such blocks pointless, but maybe their uses aren't actually related?
Note: Sorry, I don't have any code to include. As I mentioned, I understand the syntax and the general idea of scoping, I'm just not clear on when a do ... end
block would be beneficial.
the main use i have found for "do (code) end" is limiting or setting the function environment of certain variables, for example locally setting an already made variable to something else for use inside of a certain part of the code that changed part color or some type of property in a part, or you could use get and setfenv for more fun variable changing
besides that i never really found a use for it
Yes you are right, but uses for that can be different even tho i don't use them too, you can use them as a decoration like:
function() do -- configuration assert() assert() assert() assert() assert() assert() if not x then return end end -- and here the script goes end)
Even tho you do not have to, also another use is for example having classes in one script and you would need to limit amount of variables so you do
do local class1 = {} function class1.test = true end do local class2 = {} function class1.test = true end print(class1) -- nil print(class2) -- nil
And here you prevented uneccessary variables, overall it's mostly useless but i have found it a use once, for example i could split the code into modules but i needed one variable to be accessed from all the classes and defining it in every single module would be ehh so i used do for that:
local ImportantVariable = "WideSteal" do local class1 = {} ImportantVariable.LoadClass(class1) end do local class2 = {} ImportantVariable.LoadClass(class2) end
Instead of doing this in every single module
-- module 1 local ImportantVariable = "WideSteal" -- module 2 local ImportantVariable = "WideSteal"
BUT here setfenv
comes instead, if every single module will have function Init
then you can get rid of do...end
-- script local CustomEnviroment = { ImportantVariable = "WideSteal", print = print, } for module in pairs(modules) do module.init(CustomEnviroment) end -- module1 function module1.init(CustomEnviroment) setfenv(1, CustomEnviroment) print(ImportantVariable) -- WideSteal end) -- module2 function module1.init(CustomEnviroment) setfenv(1, CustomEnviroment) print(ImportantVariable) -- WideSteal end)
so basically do...end
has probably no uses except for decoration