local value = nil
print(value)
or
local value
print(value)
Both of these methods do the exact same thing, but I was wondering which one is preferred more.
local value = nil
print(value)
or
local value
print(value)
Both of these methods do the exact same thing, but I was wondering which one is preferred more.
They are both the same. What are you trying to do? The only difference is that the former is more explicit. nil
is an expression and that is how you can write it.
There is no ârightâ or âwrongâ way to do it
In my opinion,
the ârightâ way would just be local var
Iâm not trying anything. I was just curious because I remember this question being brought up a while ago and there was debate on which one was considered the ârightâ way.
One isnât more correct than the other, they are same.
That is like arguing between
local function f() end
and
local f; f = function() end
They are the same.
Either one is perfectly acceptable. There is really no difference whatsoever, except that âvariable = nilâ is slightly more clear in my opinion, as compared to just not setting a value for the variable at all. You then know when reading through the code, that the variable does now for certain equal nil, and that you are not just referencing it again without changing the value. Just a personal preference.
The proper and best practice is value = nil;
First and foremost, readability. Itâs always nice to see the value when skimming through code. Now, hereâs the fun part.
When initializing a variable, a slot in computer memory is allocated for that variable. That slot in memory could contain garbage data left behind by any program that utilized that memory slot. With that being said, just typing âlocal valueâ without it being initialized will actually be:
local value = (whichever data is in the memory slot)
Initializing value to nil guarantees expected behavior. Not doing so may have a block of code not giving the desired output because whatever garbage data resides in the memory is not ânilâ.
However, depending on certain engines and frameworks. Some do initialize non initialized variables. Iâm pretty sure ROBLOX initializes anything to nil under the hood if not specified. But many other engines do not, thus leaving uninitialized variables pointing to random, garbage data that was left behind by another program on your computer. Which leads to unexpected behavior.
Fortunately Lua(u) doesnât do this. local x
just sets x
to nil and is a common idiom of pre-declaring a variable
Yes, fortunately ROBLOX LUA does set it to nil. But for best practice, initialized variables is the way to go.