Make function which changes varriable

Perhaps it is worth mentinoning that:

  1. Scalars cannot be changed by default. They are immutable values. You can change, however, the value associated with the label a, and to do so you you better return the value from your function:
function foo(a)
    a = a + 1
    return a
end

and then call this function with

a = foo(a)

From a user perspective, this will change the value associated to a in the scope where the function was called from. This does not mean that the “previous a” has changed, but the value associated to the label a is another one now.

  1. Arrays can be changed, they are mutable. And that is why your example with a=[2] works. This is fine to do, but generally it is thought to be used for larger arrays, because there is where “changing” the values in the same position in memory is worth relative to just copying the values.
3 Likes