granite-docs/docs/value-cloning.md
2024-08-16 14:48:06 +01:00

1.4 KiB

Value cloning

Sometimes in Granite, you may want to clone variables. This is fairly easy with one operation!

New operations

  • :%(source),(target), variable clone, sets (target) to the value in (source)

Tutorial

Imagine you want to create a program to calculate a Fibonacci sequence up to a certain term.

The first two numbers of the sequence are 0 and 1 and each next term is the sum of the previous two meaning that number #3 is number #1 (0) plus number #2 (1)

We can begin the program by initialising and printing the first terms and the counter and asking the user for a term:

:0 Init variables and ask user for term
:?a
:>2,i
:>0,x
:>1,y
:>0,z

:0 print term 0 and term 1 and stop if user didnt want more
:!x
:=exit,a,0
:!y
:=exit,a,1

:0 increment a for loop purposes
:^a

Now for the loop, first we want to perform the addition and increment i:

:@loop
:ax,y,z
:!z
:^i

Now we want to move the new term into y and the y term into x.

:%y,x
:%z,y

We need to clone the y term into x first

Now add the loop operation and premature exit label.

:-loop,i,a
:@exit
:~

Now run the program, you'll get an output similar to this after entering a number:

? 12
0
1
1
2
3
5
8
13
21
34
55
89
144

Congratulations! Now you can clone variables!

After example

:?a
:>2,i
:>0,x
:>1,y
:>0,z
:!x
:=exit,a,0
:!y
:=exit,a,1
:^a
:@loop
:ax,y,z
:!z
:^i
:%y,x
:%z,y
:-loop,i,a
:@exit
:~