# How can I execute code depending on a die value in AnyDice?

I'd like to be able to have a conditional test the value of a die or set of dice. Here's a simple example using a d6, but I'm looking for a way to check values of arbitrary dice sets.

X: 1d6

if X = 1 {
\execute arbitrary code\
output 0
}
if X = 2 {
\execute other arbitrary code\
output 1
}
\and so on for other values of X.\


If you plug this into AnyDice right now, you'll get this rather unhelpful error.

calculation error
Boolean values can only be numbers, but you provided "d{?}".
Depending on what you want, you might need to create a function.

I searched the documentation and function library for a way to typecast the die value to a number so that it could work in booleans, but found nothing. I tried creating a separate variable to hold the boolean, as seen here:

X: 1d6
Y: X = 1

if Y {
...


But that didn't work either. I looked at several other questions related to looking for unusual values in AnyDice, but they all use various probability tricks to solve the specific problem instead of applying a general solution. This question mentions the [count] function, so I tried using that, but to no avail.

X: 1d6

if [count 1 in X] = 1 {
...


This outputs the same error as the code above. With a tool as powerful as AnyDice, there must be a way to do something as simple as execute code based on the value of a die. How can this be done?

• Part of the trouble here is that you're thinking that X contains the value of one roll of 1d6, but AnyDice thinks it contains a list of all possible results of rolling 1d6. You will need a completely different conceptual approach than you're using, as what you're attempting will never do what you're expecting. (That's why those other questions use probability tricks: AnyDice only deals in probability.) So what are you actually trying to do, so we can help with that? – SevenSidedDie Feb 5 '15 at 22:48
• I'm looking for a general way to represent rolls that depend on other rolls. For example, it's not that uncommon for rules to say things like "if you roll a 6 in this group of d6s, add another d6" or "if you roll a 20 on your attack roll, roll again to confirm the critical hit". I'm trying to simulate any general scenario in which the outcome of one roll determines what other rolls are made. – kigaltan Feb 5 '15 at 22:58

What you need to do is have your conditional inside a function with a number parameter. Then when you pass it a die, anydice will roll the die at that time and use the result in the function.

function: X:n conditional {

if X = 1 {execute arbitrary code here}

if X = 2 {execute arbitrary code here}

if X = 3 {execute arbitrary code here}

if X = 4 {execute arbitrary code here}

if X = 5 {execute arbitrary code here}

if X = 6 {execute arbitrary code here}

}

output [d6 conditional]


There are some slightly more practical examples of this technique in my answer here.