ZenScript icon indicating copy to clipboard operation
ZenScript copied to clipboard

Varargs in functions

Open PrincessRTFM opened this issue 4 years ago • 2 comments

Looking at the CraftTweaker documentation for IOreDictEntry, the example for adding items indicates that varargs functions exist, as shown here:

//oreDictEnt.add(IItemStack... item_items);
oreDictEnt.add(<minecraft:grass>);
oreDictEnt.add(<minecraft:iron_ore>, <minecraft:dirt>);

However, nowhere in the documentation for custom functions is there any indication of it being possible to declare a custom function to take a varargs parameter. I tried, as a quick test, declaring a function parameter parameterName as string... (and it was not just the last but the only parameter in that function) but running /ct syntax gave me the error ) expected at that line. I also tried declaring parameterName... as string[] and got the same error.

Can custom functions be declared to take varargs parameters? If so, what is the syntax (and can it be added to the documentation)? If not, can this be implemented?

Final note: I felt this belonged in the ZenScript issue tracker because it's a feature inherent to the language, not the minecraft-specific application of it. If I'm wrong about that, I can open a copy of this on the CraftTweaker issue tracker instead.

PrincessRTFM avatar Jun 08 '20 01:06 PrincessRTFM

Unrelated side note, I love that github markdown syntax highlighting understands zenscript as a language.

PrincessRTFM avatar Jun 08 '20 01:06 PrincessRTFM

ZS supports the idea of varargs. However, currently only methods that are declared in the Java Code allow for varargs.

Custom functions in ZS are still pretty limited. They do not allow for varargs. Heck, normal functions don't even allow for overloading or optional parameters.

If you are looking on how to use varargs when in Java Code, you can see here https://github.com/CraftTweaker/CraftTweaker/blob/1.12/CraftTweaker2-API/src/main/java/crafttweaker/api/oredict/IOreDictEntry.java#L24

Since varargs are just syntactic sugar for an array creation, you can create the array explicitly. Or you could create a zenClass inside ZS code, and have overloads for the most cases, so something like

zenClass MyClass {
    zenConstructor(){}
    function doSomething() as void {doSomething([]);}
    function doSomething(arg0 as string) as void {doSomething([arg0]);}
    function doSomething(arg0 as string, arg1 as string) as void {doSomething([arg0, arg1]);}
    function doSomething(arg0 as string, arg1 as string, arg2 as string) as void {doSomething([arg0, arg1, arg2]);}
    function doSomething(arg0 as string, arg1 as string, arg2 as string, arg3 as string) as void {doSomething([arg0, arg1, arg2, arg3]);}
    function doSomething(varargs as string[]) as void{
        /*Code here*/
    }
}

kindlich avatar Jun 08 '20 05:06 kindlich