You can easily check for in-game conditions using Sandstone's builtin
if
statement, or loop while a condition is true using while
.If Syntax
To check a condition (see Conditions), the following syntax is used:
_
.if(condition1, () => {
say('Condition 1 is true')
})
.elseIf(condition2, () => {
say('Condition 2 is true')
})
.else(() => {
say('Both condition 1 and condition 2 are false')
})
As you can see, this syntax mimics the original
if / else if / else
construct
from classical programming languages.elseIf
and else
are optional. You can chain as many elseIf
as needed:_.if(condition1, () => {
say('I am a lonely if')
})
_
.if(condition2, () => {
say(2)
})
.elseIf(condition3, () => {
say(3)
})
.elseIf(condition4, () => {
say(4)
})
While
Syntax
while
uses the same syntax as if
:_.while(condition, () => {
say('The condition is true')
}
Under the hood,
while
uses recursion. Having a lot of iterations is costly and should be avoided.Sandstone also implements
do while
, which always run at least once:_.doWhile(condition, () => {
say('The condition is true, or this is the 1st iteration!')
})
Context Modifiers
This feature is planned, but not available yet.
When using recursion in Minecraft, you might change the context of each function call. For example, a raycast will go one block further at each recursion.
while
gives you the possibility to modify the context at each iteration:_.while(condition, () => {
say('The condition is true!')
return execute.positioned('^ ^ ^1')
})
This example will compile to:
## namespace:main
execute if condition run namespace:main/while
## namespace:main/while
say The condition is true!
execute positioned ^ ^ ^1 if condition run namespace:main/while
Success Callback
This feature is planned, but not available yet.
When the condition becomes false, you can run some commands using the latest context. For example, a raycast might change a block when the condition is not met anymore.
This callback is the third argument of the
while
method:_.while(condition, () => {
say('The condition is true')
}, () => {
say('The condition just became false!')
})
Examples
Give 1 diamond to the player for each kill he has:
const kills = Objective.create('kills', 'playerKillCount')
const i = Variable(0)
_.while(i.lessThan(kills('@s'), () => {
give('@s', 'minecraft:diamond', 1)
i.add(1)
})
Raycast until you find a block thatβs not air, and replace it with a
diamond_block
:_.while(_.block('~ ~ ~', 'minecraft:air'), () => {
return execute.positioned('^ ^ ^1')
}, () => {
setblock('~ ~ ~', 'minecraft:diamond_block')
})