Discord
Login
Community
DARK THEME

The scope of the local variable's visibility.

https://microstudio.dev/i/Loginus/localobject/

When I create a local variable of the number type and I refer to this variable in the anonymous function, after leaving the anonymous function the local numeric variable has no value assigned.

When I create a local variable of the LIST type and refer to this variable in the anonymous function, then after exiting the anonymous function, the local variable of the LIST type has assigned values.

Both data types should behave the same. Either they can be used in an anonymize function, or they cannot, and then there should be a warning about the use of an undeclared variable.

There is a lot to cover to explain it. That's a good opportunity to clarify a few concepts:

mutable vs immutable data types

Like many scripting languages, microScript has some mutable data types and some immutable data types:

  • immutable: numbers, strings
  • mutable: objects, lists

A variable containing a mutable data must be understood as a pointer to the object or list. If you assign it to a new variable, you are not creating a copy of the object or the list, you are just making a pointer to the same object or list. When doing a = b = [1,2,3], you are creating just one list, with two pointers to it a and b. If you modify a, you also modify b as they are the same list or object. If you want to create a copy, you have to do it explicitly (a simple way to copy a list is a = b + [] by the way).

+= operator for lists

The += operator for lists acts as syntactic sugar for list.push(item) ; thus while number += x assigns a new, immutable number number + x to variable number, list += element does not change the value of the variable list (still a pointer to the very same list object), it just appends an element to the list, thus mutates it.

borrowing outer local variables when defining functions

When you define a function in a context where some local variables are defined, you can borrow the local variables in your function. Borrowing happens by value and not by reference. It means your function cannot change the value of the outer local variable ; the function has its own copy of the outer local variable, which value is set, when the function begins, to the value the variable had when the function was first defined.

Example:

local x = 1
f1 = function()
  return x
end
x = 2
f2 = function()
  return x
end
print(f1()) // output: 1
print(f2()) // output: 2

I hope all this helps to clarify what is happening in your code example :-)

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community