Which is the "right" way to create a nil value?

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.

2 Likes

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

2 Likes

Yes, fortunately ROBLOX LUA does set it to nil. But for best practice, initialized variables is the way to go.

2 Likes