(Redirected from Making Temporary Variables)

Although there is no built in function for creating temporary variables while a project is running, it is possible to simulate it by using lists.

Creating Temporary Variables

To start out, make two lists, "Variables", and "Data". Then, make the following custom block:

define create variable (name)
add (name) to [Variables v]
add [0] to [Data v]

Setting Temporary Variables

Next, you need to be able to set temporary variables. There are two blocks, one for setting the value, and for changing the value, similar to Set () to () and Change () by ().

define set (variable) to (value)
if <[Variables v] contains (variable)> then //Check to see if the variable exists
set [i v] to [1]
repeat until <(item (i) of [Variables v]) = (variable)> //Find the index of the variable
change [i v] by (1)
end
replace item (i) of [Data v] with (value) //Replace the matching value with the new one
end

define change (variable) by (value)
if <[Variables v] contains (variable)> then //Check to see if the variable exists
set [i v] to [1]
repeat until <(item (i) of [Variables v]) = (variable)> //Find the index of the variable
change [i v] by (1)
end
replace item (i) of [Data v] with ((item (i) of [Data v]) + (value)) //Change the matching value
end

Retrieving Values

Because there is not yet a way to make custom reporters a separate variable has to be set to the value wanted in order to actually use temporary variables in a project. The variable that contains the value will be called "Temp".

define get (variable)
if <[Variables v] contains (variable)> then //Check to see if the variable exists
set [i v] to [1]
repeat until <(item (i) of [Variables v]) = (variable)> //Find the index of the variable
change [i v] by (1)
end
set [Temp v] to (item (i) of [Data v]) //Set a readable value to the variable's value
end

Hacked set Block

It is possible to create and set variables while a project is running by modifying a project external to the normal Scratch editor. Once a variable has been created through a script, though, it can only be deleted manually.

These variables are not temporary, though—but variables that are considered deleted can either be marked with a special value; or have their names added to a list to keep track of such deletion.

These variables are also much more efficient since they use the builtin hashmap to access and set them.

define set (name) to (value)
set (name) to (value)

The above custom block will create a local variable if one does not yet exist. It will then assign the value of the (value::custom) parameter to that variable.

The value of a variable can be determined like so:

define get (name)
set [result v] to ((name) of [Sprite1 v])

With "Sprite1" replaced with the sprite that has created the variable.