so, recently i’ve been taking a look at some scripts and have found several instances of the following:
something like this
local var = {} do
if math.random() == 0 then
var = nil
end
How does this work? is this bad practice?
so, recently i’ve been taking a look at some scripts and have found several instances of the following:
something like this
local var = {} do
if math.random() == 0 then
var = nil
end
How does this work? is this bad practice?
(correct me if I am wrong please)
First, this creates a table and puts it to a local variable named var
. The do
after it creates a scope that you can use var
variable everywhere before its end
(although doing do
just creates a scope and runs like normal, people like to use it to keep local variables inside their scope).
I heard people do that because they want to guarantee that the variable can be used in the entire scope.
local var = {}
do
-- code!
end
math.random()
is a function that by default, returns 0 or 1. If the number is 0, then it’ll go to the next line, else, does nothing.
When the if
statement is true, it will change the variable var
to nil, and I think if you were to use var
before the if statement or the math.random
is one, it will still result to an empty table.
I don’t know if this is bad practice or not. For this script, I do not know why it’s using it, it seems to be quite random. For the do
though, I wouldn’t think it’s a bad practice. In that script, you’re only declaring a variable and creating a scope which runs the same as not having one, but only local variables inside that scope can’t use it.
Ok, thanks for taking the time to reply with such a detailed answer
It’s a one in 2^53 probability for math.random to return 0 and to turn var into a nil variable so a almost close to zero. *Assuming math.random implementation is similar to javascript.
In most cases this will break the script if it does not account for var being a nil variable. Is this bad practice? Maybe not if you want your script to break just pretty unnecessary and weird.
So yeah maybe mark @H20mac as the best answer.
Yeah it was just an example, I was mostly confused about placing do
right after setting a variable and using it to change said variable.
You are correct.
It’s also worth mentioning that writing a do-block about a variable is generally used for code formatting (you can open and close that variable’s contents in code editor). As an example, we do it for our DevProduct functions.
This section of code is clunky and unimportant visually past its initial write, so the ability to close it easily adds pace to workflow.
That makes sense, I am writing some OOP code and this will come in quite handy lol
the main problem is that their code needs two end’s, not just one end
local var = {} do
if math.random() == 0 then
var = nil
end
end
this is the working code if do
is used