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 one 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
replace item (item # of (variable) in [Variables v]) of [Data v] with (value) //Replace the existing variable's value with the new one
end

define change (variable) by (value)
if <[Variables v] contains (variable)> then //Check to see if the variable exists
replace item (item # of (variable) in [Variables v]) of [Data v] with ((item (item # of (variable) in [Variables v]) of [Data v]) + (value)) //Change the variable's value by the amount specified
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 [Temp v] to (item (item # of (variable) in [Variables v]) of [Data v]) //Set a readable value to the variable's value
end

Hacked set Block

In Scratch 2.0, 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 variables that are considered deleted could 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 built-in hashmap to access and set them.

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

The custom block above 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.

Cookies help us deliver our services. By using our services, you agree to our use of cookies.