Variables โ
Local SmartPy variables can be defined as follows: x = sp.local("x",ย 0)
The first argument to sp.local
is a string that will be used in error messages. It is advisable to use the same name that is used on the left of =.
Local variable values can be accessed to and updated with the .value field: x.valueย =ย 1, x.valueย =ย 2ย * x.valueย +ย 5
.
Local variables are necessary when the variable is mutated inside if's
and loop's
.
Local variables can be marked as immutable by specifying mutable =ย False
.
Local SmartPy variables are different from Python
variables. The latter cannot be updated during contract execution. :::
As an example, here is how we can compute a square root.
python
@sp.entrypoint
def squareRoot(self, x):
sp.verify(x >= 0)
y = sp.local('y', x)
sp.while y.value * y.value > x:
y.value = (x // y.value + y.value) // 2
sp.verify((y.value * y.value <= x) & (x < (y.value + 1) * (y.value + 1)))
self.data.value = y.value