I am working on relearning lua,
I need help on the do statement I mean its in lua for a reason
but I need a more clear explanation on it and how it works. I read a short explanation somewhere on the other post that I posted below but I need a much more clear explanation. Thank you.
“do – I don’t do anything special, but I have my own set of locals, which is called a scope.
print(abc) – I can’t see the variable yet, so I access a global, but since there is no global named that I will print “nil” which means no value. It’s sort of like “null” in other programming languages.
local abc = 123 – I only exist inside of my scope, under this do statement, and I can be used by future code
– Everything past here can see the abc local now:
print(abc) – prints 123
end”
A do
statement just creates its own block. Local variables inside a scope can only be accessed within that scope.
do
local x = 5
end
print(x)
This will print nil
because x
is not in the scope that the print
is.
The lua site has a section dedicated to scope and blocks
https://www.lua.org/pil/4.2.html
It’s not really used all that often unless you really need a specific scope.
and what are the times lets say I need to use a specific scope for if you dont mind me asking
I couldn’t tell you… I’ve never once used it before in my years of using lua, I’ve never found a use for it. Though maybe someone else could tell you
Sometimes it looks better to have code which aren’t variable declarations inside of do end blocks. Also you may do this to avoid polluting the namespace (use multiple variables with the same name which aren’t related to one another).
do
local CanCo = workspace:GetChildren()
for i, v in pairs(CanCo) do
if v:IsA(“BasePart”) then
v.CanCollide = false
end
end
end
They are just like brackets for locals.
Any Locals, inside of an If statemnet, or any chucnk, ending with an End, are locals
At the begining of this scriot, I un-colide every part in workspace. But never have to do that again or use the list, so I’m hoping it all vanishes, after the End.