3.5 Values and Variables

Up to now we have worked with byte values, either writing them in the REPL or mapping them at the current IO space. Often it is useful to save values under meaningful names, and access to them by name. In poke we do that by storing the values in variables.

Before being used, variables shall be defined using the var construction. Let’s get the byte at offset 64 bytes and save it in a variable called foo:

(poke) var foo = byte @ 64#B

This defines a new variable (foo) and initializes it to the value of the byte at offset 64 bytes. This results on foo to hold the value 37.

Once defined, we can get the value of a variable by just giving its name to poke:

(poke) foo
37UB

Several variables can be defined in a single var declaration. Each definition is separated by a comma. This is equivalent of issuing several vars:

(poke) var a = 10, b = 20

In general, a variable containing a byte value can be used in any context where the contained value would be expected. If we wanted to check the highest bit in the byte value stored in foo we would do:

(poke) foo & 0x80
0x0

Assigning a value to a variable makes the value the new contents of the variable. For example, we can increase the value of foo by one like this:

(poke) foo = foo + 1

At this point, an important question is: when we change the value of the variable foo, are we also changing the value of the byte stored in foo.o at offset 64 bytes? The answer is no. This is because when we do the mapping:

(poke) var foo = byte @ 64#B

The value stored in foo is a copy of the value returned by the map operator @. You can imagine the variable as a storage cell located somewhere in poke’s memory. After the assignment above is executed there are two copies of the byte value 0x25: one in foo.o at offset 64 bytes, and the other in the variable foo.

It follows that if we wanted to increase the byte in the file, we would need to do something like:

(poke) var foo = byte @ 64#B
(poke) foo = foo + 1
(poke) byte @ 64#B = foo

Or, more succinctly, omitting the usage of a variable:

(poke) byte @ 64#B = (byte @ 64#B) + 1

Or, even more succinctly:

(poke) (byte @ 64#B) += 1

Note how we have to use parenthesis around the map at the right hand side, because the map operator @ has less precedence than the plus operator +.