Skip to content

Commit e45f428

Browse files
committed
Add loops to docs
1 parent 1955959 commit e45f428

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

website/docs/language/contracts.md

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -122,8 +122,8 @@ hashedValue = sha256(hashedValue);
122122
myString = 'Cash';
123123
```
124124

125-
### Control structures
126-
The only control structures in CashScript are `if...else` statements. This is due to limitations in the underlying Bitcoin Script which prevents loops, recursion, and `return` statements. If-else statements follow usual semantics known from languages like C or JavaScript.
125+
### If statements
126+
If and if-else statements follow usual semantics known from languages like C or JavaScript. If the condition within the `if` statement evaluates to `true`, the block of code within the `if` statement is executed. If the condition evaluates to `false`, the block of code within the optional `else` statement is executed.
127127

128128
:::note
129129
There is no implicit type conversion from non-boolean to boolean types. So `if (1) { ... }` is not valid CashScript and should instead be written as `if (bool(1)) { ... }`
@@ -149,6 +149,31 @@ contract OneOfTwo(bytes20 pkh1, bytes32 hash1, bytes20 pkh2, bytes32 hash2) {
149149
}
150150
```
151151

152+
### Loops (beta)
153+
154+
Currently, CashScript only supports `do {} while ()` loops in the 0.13.0-next.0 pre-release. More advanced loop constructs will be added in the full 0.13.0 release. Keep in mind that in a `do {} while ()` loop, the condition is checked *after* the block of code within the loop is executed. This means that the block of code within the loop will be executed at least once, even if the condition is initially `false`.
155+
156+
:::caution
157+
Loops in CashScript are currently in beta and may not fully behave as expected with debugging and console.log statements. The syntax for loops may change in the future.
158+
:::
159+
160+
#### Example
161+
```solidity
162+
pragma cashscript ^0.13.0;
163+
164+
contract NoTokensAllowed() {
165+
function spend() {
166+
int inputIndex = 0;
167+
168+
// Loop over all inputs (variable length), and make sure that none of them contain tokens
169+
do {
170+
require(tx.inputs[inputIndex].tokenCategory == 0x);
171+
inputIndex = inputIndex + 1;
172+
} while (inputIndex < tx.inputs.length);
173+
}
174+
}
175+
```
176+
152177
### console.log()
153178
The `console.log` statement can be used to log values during debug evaluation of a transaction. Any variables or primitive values (such as ints, strings, bytes, etc) can be logged. You can read more about debugging in the [debugging guide](/docs/guides/debugging).
154179

0 commit comments

Comments
 (0)