Initializing an object with `nothing`

I am curious whether initializing a variable of type T using the following code is any good for type stability. The type is usually alot more complex than the example used below with significant allocations and a dependence on the conditions, so I don’t want to initialize a full instance before the if-statement with dummy input, too much waste. On the other hand, if declared inside the if statement, it will not be visible outside, and that’s a no go. I also couldn’t find a way to initialize a global-but-not-too-global variable inside an if statement, so the following seems like the next most reasonable approach.

a = nothing
if b > 1
     a = T(1)
else
     a = T(2)
end
1 Like

if declared inside the if statement, it will not be visible outside

I don’t think this is true - if blocks don’t introduce new scope. Do you have a minimum working example of a case where you can’t access something allocated inside an if block?

1 Like

Also, it’ll hurt type stability and the syntax for declaring local variable is local.

1 Like

I had a few cases before where declaring a variable with nothing seemed to have solved an error, so I thought this was true. Thanks for correcting me. I will remove this declaration.

Variables declared inside a for-loop on the other hand are not visible outside the for-loop. What’s the preferred way of making them visible outside?

local x
for it in iter
  x = something 
end

Perhaps?

Yes.

is this still correct for an array.

What is still correct for an array?

if i define an array with local without initializing is it allowed. thanks

You can declare a variable, including an array, without initializing the variable. Defining the array IS initializing it.