Do Minecraft functions have inputs and outputs like conventional functions?

Now I know that technically in theory one could just use blocks to convey values in and out of any body of code. What I'm asking is whether or not a built-in syntax exists for input parameters and return values similar to what pretty much all other programming languages consider to be functions?


Solution 1:

A function in Minecraft and a function in programming is completely different.

A function in Minecraft is just a list of commands, which can be executed in game with a single command, running commands in the function from top to bottom. The only other thing you can do with functions right now is leave comments in the code, which start with a #.

So to answer both of your questions; no.

Solution 2:

While it's true that functions don't take any inputs or return any outputs, there are ways to fake it. A good way to conceptualize it is to look under the hood of how a language like C++ actually does function calls. Take this function declaration:

public list<Player> Foo(int a, int b);

When that function is called, the calling code pushes the values of a and b on to the top of the stack. The function will pop those values off, and just before it's finished, it'll push the list of players on at the same place a was for the calling code to continue to use.

Now we don't have a stack that we can use when making command contraptions, but we do have some things that are almost as good: scoreboards and tags. In C++, the function knows (relative to the stack pointer) where a and b are, and where to put the list<Player> when it's done. In Minecraft, we can use scoreboard values to pass around ints, tags to pass around players and entities, and tagged armor stands to pass around coordinates, and use the name of the function in those scoreboards and tags so the function knows where to look.

So let's see how the above C++ function might look in Minecraft commands. First, we need to pass in our two integers. We'll use a fake scoreboard player for this:

scoreboard objectives add a dummy
scoreboard objectives add b dummy
scoreboard players set #Foo a 1
scoreboard players set #Foo b 5

After this, we can just call the function:

function MyNamespace:Foo

To return the list of players, a command similar to this one inside Foo can be used:

scoreboard players tag @a[<some selector>] add FooResult

In the calling portion we can then use those tagged players in another command:

tell @a[tag=FooResult] Hello!

This is just one relatively simple example, but hopefully it shows that there's a lot of complexity that can be added to commands and functions.