Search in sources :

Example 1 with VariableString

use of ch.njol.skript.lang.VariableString in project Skript by SkriptLang.

the class EffBroadcast method execute.

@Override
@SuppressWarnings("deprecation")
public void execute(Event e) {
    List<CommandSender> receivers = new ArrayList<>();
    if (worlds == null) {
        receivers.addAll(Bukkit.getOnlinePlayers());
        receivers.add(Bukkit.getConsoleSender());
    } else {
        for (World world : worlds.getArray(e)) receivers.addAll(world.getPlayers());
    }
    for (Expression<?> message : messages) {
        if (message instanceof VariableString) {
            BaseComponent[] components = BungeeConverter.convert(((VariableString) message).getMessageComponents(e));
            receivers.forEach(receiver -> receiver.spigot().sendMessage(components));
        } else if (message instanceof ExprColoured && ((ExprColoured) message).isUnsafeFormat()) {
            // Manually marked as trusted
            for (Object realMessage : message.getArray(e)) {
                BaseComponent[] components = BungeeConverter.convert(ChatMessages.parse((String) realMessage));
                receivers.forEach(receiver -> receiver.spigot().sendMessage(components));
            }
        } else {
            for (Object messageObject : message.getArray(e)) {
                String realMessage = messageObject instanceof String ? (String) messageObject : Classes.toString(messageObject);
                receivers.forEach(receiver -> receiver.sendMessage(realMessage));
            }
        }
    }
}
Also used : Effect(ch.njol.skript.lang.Effect) CommandSender(org.bukkit.command.CommandSender) Name(ch.njol.skript.doc.Name) ChatMessages(ch.njol.skript.util.chat.ChatMessages) ExpressionList(ch.njol.skript.lang.ExpressionList) Event(org.bukkit.event.Event) ParseResult(ch.njol.skript.lang.SkriptParser.ParseResult) ArrayList(java.util.ArrayList) LiteralUtils(ch.njol.skript.util.LiteralUtils) Since(ch.njol.skript.doc.Since) Expression(ch.njol.skript.lang.Expression) BungeeConverter(ch.njol.skript.util.chat.BungeeConverter) BaseComponent(net.md_5.bungee.api.chat.BaseComponent) List(java.util.List) Examples(ch.njol.skript.doc.Examples) Nullable(org.eclipse.jdt.annotation.Nullable) Classes(ch.njol.skript.registrations.Classes) World(org.bukkit.World) VariableString(ch.njol.skript.lang.VariableString) ExprColoured(ch.njol.skript.expressions.ExprColoured) Skript(ch.njol.skript.Skript) Description(ch.njol.skript.doc.Description) Kleenean(ch.njol.util.Kleenean) Bukkit(org.bukkit.Bukkit) ExprColoured(ch.njol.skript.expressions.ExprColoured) BaseComponent(net.md_5.bungee.api.chat.BaseComponent) ArrayList(java.util.ArrayList) VariableString(ch.njol.skript.lang.VariableString) CommandSender(org.bukkit.command.CommandSender) VariableString(ch.njol.skript.lang.VariableString) World(org.bukkit.World)

Example 2 with VariableString

use of ch.njol.skript.lang.VariableString in project Skript by SkriptLang.

the class EffMessage method execute.

@Override
protected void execute(Event e) {
    Player sender = this.sender != null ? this.sender.getSingle(e) : null;
    CommandSender[] commandSenders = recipients.getArray(e);
    for (Expression<?> message : messages) {
        Object[] messageArray = null;
        List<MessageComponent> messageComponents = null;
        for (CommandSender receiver : commandSenders) {
            if (receiver instanceof Player && message instanceof VariableString) {
                if (messageComponents == null)
                    messageComponents = ((VariableString) message).getMessageComponents(e);
            } else {
                if (messageArray == null)
                    messageArray = message.getArray(e);
            }
            if (receiver instanceof Player) {
                // Can use JSON formatting
                if (message instanceof VariableString) {
                    // Process formatting that is safe
                    sendMessage((Player) receiver, sender, BungeeConverter.convert(messageComponents));
                } else if (message instanceof ExprColoured && ((ExprColoured) message).isUnsafeFormat()) {
                    // Manually marked as trusted
                    for (Object object : messageArray) {
                        sendMessage((Player) receiver, sender, BungeeConverter.convert(ChatMessages.parse((String) object)));
                    }
                } else {
                    // It is just a string, no idea if it comes from a trusted source -> don't parse anything
                    for (Object object : messageArray) {
                        List<MessageComponent> components = ChatMessages.fromParsedString(toString(object));
                        sendMessage((Player) receiver, sender, BungeeConverter.convert(components));
                    }
                }
            } else {
                // Not a player, send plain text with legacy formatting
                for (Object object : messageArray) {
                    receiver.sendMessage(toString(object));
                }
            }
        }
    }
}
Also used : ExprColoured(ch.njol.skript.expressions.ExprColoured) Player(org.bukkit.entity.Player) VariableString(ch.njol.skript.lang.VariableString) CommandSender(org.bukkit.command.CommandSender) MessageComponent(ch.njol.skript.util.chat.MessageComponent) ExpressionList(ch.njol.skript.lang.ExpressionList) List(java.util.List) VariableString(ch.njol.skript.lang.VariableString)

Example 3 with VariableString

use of ch.njol.skript.lang.VariableString in project skript-reflect by TPGamesNL.

the class CustomSyntaxSection method handleUsableSection.

@SuppressWarnings("unchecked")
protected boolean handleUsableSection(SectionNode sectionNode, Map<T, List<Supplier<Boolean>>> usableSuppliers) {
    File currentScript = SkriptUtil.getCurrentScript();
    for (Node usableNode : sectionNode) {
        String usableKey = usableNode.getKey();
        assert usableKey != null;
        Supplier<Boolean> supplier;
        if (usableKey.startsWith("custom event ")) {
            String customEventString = usableKey.substring("custom event ".length());
            VariableString variableString = VariableString.newInstance(customEventString.substring(1, customEventString.length() - 1));
            if (variableString == null || !variableString.isSimple()) {
                Skript.error("Custom event identifiers may only be simple strings");
                return false;
            } else {
                String identifier = variableString.toString(null);
                supplier = () -> {
                    if (!getParser().isCurrentEvent(BukkitCustomEvent.class))
                        return false;
                    EventSyntaxInfo eventWhich = CustomEvent.lastWhich;
                    return CustomEventUtils.getName(eventWhich).equalsIgnoreCase(identifier);
                };
            }
        } else {
            JavaType javaType = CustomImport.lookup(currentScript, usableKey);
            Class<?> javaClass = javaType == null ? null : javaType.getJavaClass();
            if (javaClass == null || !Event.class.isAssignableFrom(javaClass)) {
                Skript.error(javaType + " is not a Bukkit event");
                return false;
            }
            Class<? extends Event> eventClass = (Class<? extends Event>) javaClass;
            supplier = () -> getParser().isCurrentEvent(eventClass);
        }
        whichInfo.forEach(which -> usableSuppliers.computeIfAbsent(which, (whichIndex) -> new ArrayList<>()).add(supplier));
    }
    return true;
}
Also used : EntryNode(ch.njol.skript.config.EntryNode) InvalidNode(ch.njol.skript.config.InvalidNode) SectionNode(ch.njol.skript.config.SectionNode) Node(ch.njol.skript.config.Node) VoidNode(ch.njol.skript.config.VoidNode) VariableString(ch.njol.skript.lang.VariableString) VariableString(ch.njol.skript.lang.VariableString) EventSyntaxInfo(com.btk5h.skriptmirror.skript.custom.event.EventSyntaxInfo) BukkitCustomEvent(com.btk5h.skriptmirror.skript.custom.event.BukkitCustomEvent) JavaType(com.btk5h.skriptmirror.JavaType) BukkitCustomEvent(com.btk5h.skriptmirror.skript.custom.event.BukkitCustomEvent) Event(org.bukkit.event.Event) SelfRegisteringSkriptEvent(ch.njol.skript.lang.SelfRegisteringSkriptEvent) SkriptEvent(ch.njol.skript.lang.SkriptEvent) CustomEvent(com.btk5h.skriptmirror.skript.custom.event.CustomEvent) File(java.io.File)

Example 4 with VariableString

use of ch.njol.skript.lang.VariableString in project LifeSkript by LifeMC.

the class JavaClasses method init.

public static final void init() {
    Classes.registerClass(new ClassInfo<>(Object.class, "object").user("objects?").name("Object").description("The supertype of all types, meaning that if %object% is used in e.g. a condition it will accept all kinds of expressions.").usage("").examples("").since("1.0"));
    Classes.registerClass(new ClassInfo<>(Number.class, "number").user("num(ber)?s?").name("Number").description("A number, e.g. 2.5, 3, or -9812454.", "Please note that many expressions only need integers, i.e. will discard any frational parts of any numbers without producing an error.").usage("<code>[-]###[.###]</code> (any amount of digits; very large numbers will be truncated though)").examples("set the player's health to 5.5", "set {_temp} to 2*{_temp} - 2.5").since("1.0").defaultExpression(new SimpleLiteral<>(1, true)).parser(new Parser<Number>() {

        @Override
        @Nullable
        public Number parse(final String s, final ParseContext context) {
            try {
                if (SkriptParser.isInteger(s))
                    return Long.valueOf(s);
            } catch (final NumberFormatException e) {
                Skript.exception(e);
            }
            try {
                if (s.endsWith("%")) {
                    final String str = s.substring(0, s.length() - 1);
                    if (!SkriptParser.isIntegerOrDouble(str))
                        return null;
                    return Double.parseDouble(str) / 100;
                }
                if (!SkriptParser.isIntegerOrDouble(s))
                    return null;
                return Double.parseDouble(s);
            } catch (final NumberFormatException e) {
                Skript.exception(e);
                return null;
            }
        }

        @Override
        public String toString(final Number n, final int flags) {
            return StringUtils.toString(n.doubleValue(), SkriptConfig.numberAccuracy.value());
        }

        @Override
        public String toVariableNameString(final Number n) {
            return StringUtils.toString(n.doubleValue(), VARIABLENAME_NUMBERACCURACY);
        }

        @Override
        public String getVariableNamePattern() {
            return "-?\\d+(\\.\\d+)?";
        }
    }).serializer(new Serializer<Number>() {

        @Override
        public Fields serialize(final Number n) {
            // serialised natively by Yggdrasil
            throw new IllegalStateException();
        }

        @Override
        public boolean canBeInstantiated() {
            return true;
        }

        @Override
        public void deserialize(final Number o, final Fields f) throws StreamCorruptedException {
            assert false;
        }

        // return "" + n;
        @Override
        @Nullable
        public Number deserialize(final String s) {
            if (!SkriptParser.isIntegerOrDouble(s))
                return null;
            try {
                return Integer.valueOf(s);
            } catch (final NumberFormatException ignored) {
            /* continue, re-try with double */
            }
            try {
                return Double.valueOf(s);
            } catch (final NumberFormatException e) {
                Skript.exception(e);
                return null;
            }
        }

        @Override
        public boolean mustSyncDeserialization() {
            return false;
        }
    }).math(Number.class, new NumberArithmetic()));
    Classes.registerClass(new ClassInfo<>(Long.class, "long").user("int(eger)?s?").name(ClassInfo.NO_DOC).before("integer", "short", "byte").defaultExpression(new SimpleLiteral<>(1L, true)).parser(new Parser<Long>() {

        @Override
        @Nullable
        public Long parse(final String s, final ParseContext context) {
            if (!SkriptParser.isInteger(s))
                return null;
            try {
                return Long.valueOf(s);
            } catch (final NumberFormatException e) {
                Skript.exception(e);
                return null;
            }
        }

        @Override
        public String toString(final Long l, final int flags) {
            return "" + l;
        }

        @Override
        public String toVariableNameString(final Long l) {
            return "" + l;
        }

        @Override
        public String getVariableNamePattern() {
            return "-?\\d+";
        }
    }).serializer(new Serializer<Long>() {

        @Override
        public Fields serialize(final Long n) {
            // serialised natively by Yggdrasil
            throw new IllegalStateException();
        }

        @Override
        public boolean canBeInstantiated() {
            return true;
        }

        @Override
        public void deserialize(final Long o, final Fields f) throws StreamCorruptedException {
            assert false;
        }

        // return "" + l;
        @Override
        @Nullable
        public Long deserialize(final String s) {
            if (!SkriptParser.isInteger(s))
                return null;
            try {
                return Long.parseLong(s);
            } catch (final NumberFormatException e) {
                Skript.exception(e);
                return null;
            }
        }

        @Override
        public boolean mustSyncDeserialization() {
            return false;
        }
    }).math(Number.class, new NumberArithmetic()));
    Classes.registerClass(new ClassInfo<>(Integer.class, "integer").name(ClassInfo.NO_DOC).defaultExpression(new SimpleLiteral<>(1, true)).parser(new Parser<Integer>() {

        @Override
        @Nullable
        public Integer parse(final String s, final ParseContext context) {
            if (!SkriptParser.isInteger(s))
                return null;
            try {
                return Integer.valueOf(s);
            } catch (final NumberFormatException e) {
                Skript.exception(e);
                return null;
            }
        }

        @Override
        public String toString(final Integer i, final int flags) {
            return "" + i;
        }

        @Override
        public String toVariableNameString(final Integer i) {
            return "" + i;
        }

        @Override
        public String getVariableNamePattern() {
            return "-?\\d+";
        }
    }).serializer(new Serializer<Integer>() {

        @Override
        public Fields serialize(final Integer n) {
            // serialised natively by Yggdrasil
            throw new IllegalStateException();
        }

        @Override
        public boolean canBeInstantiated() {
            return true;
        }

        @Override
        public void deserialize(final Integer o, final Fields f) throws StreamCorruptedException {
            assert false;
        }

        // return "" + i;
        @Override
        @Nullable
        public Integer deserialize(final String s) {
            if (!SkriptParser.isInteger(s))
                return null;
            try {
                return Integer.parseInt(s);
            } catch (final NumberFormatException e) {
                Skript.exception(e);
                return null;
            }
        }

        @Override
        public boolean mustSyncDeserialization() {
            return false;
        }
    }).math(Number.class, new NumberArithmetic()));
    Classes.registerClass(new ClassInfo<>(Double.class, "double").name(ClassInfo.NO_DOC).defaultExpression(new SimpleLiteral<>(1., true)).after("long").before("float", "integer", "short", "byte").parser(new Parser<Double>() {

        @Override
        @Nullable
        public final Double parse(final String s, final ParseContext context) {
            try {
                if (s.endsWith("%")) {
                    final String str = s.substring(0, s.length() - 1);
                    if (!SkriptParser.isIntegerOrDouble(str))
                        return null;
                    return Double.parseDouble(str) / 100;
                }
                if (!SkriptParser.isIntegerOrDouble(s))
                    return null;
                return Double.parseDouble(s);
            } catch (final NumberFormatException e) {
                return null;
            }
        }

        @Override
        public final String toString(final Double d, final int flags) {
            return StringUtils.toString(d, SkriptConfig.numberAccuracy.value());
        }

        @Override
        public final String toVariableNameString(final Double d) {
            return StringUtils.toString(d, VARIABLENAME_NUMBERACCURACY);
        }

        @Override
        public final String getVariableNamePattern() {
            return "-?\\d+(\\.\\d+)?";
        }
    }).serializer(new Serializer<Double>() {

        @Override
        public Fields serialize(final Double n) {
            // serialised natively by Yggdrasil
            throw new IllegalStateException();
        }

        @Override
        public boolean canBeInstantiated() {
            return true;
        }

        @Override
        public void deserialize(final Double o, final Fields f) throws StreamCorruptedException {
            assert false;
        }

        // return "" + d;
        @Override
        @Nullable
        public Double deserialize(final String s) {
            if (!SkriptParser.isIntegerOrDouble(s))
                return null;
            try {
                return Double.parseDouble(s);
            } catch (final NumberFormatException e) {
                return null;
            }
        }

        @Override
        public boolean mustSyncDeserialization() {
            return false;
        }
    }).math(Number.class, new NumberArithmetic()));
    // FIXME Implement SkriptParser#isByte and SkriptParser#isFloat to improve the performance without disabling the parsers
    if (!DISABLE_BYTE_SHORT_FLOAT) {
        Classes.registerClass(new ClassInfo<>(Float.class, "float").name(ClassInfo.NO_DOC).defaultExpression(new SimpleLiteral<>(1F, true)).parser(new Parser<Float>() {

            @Override
            @Nullable
            public Float parse(final String s, final ParseContext context) {
                try {
                    return s.endsWith("%") ? Float.parseFloat(s.substring(0, s.length() - 1)) / 100 : Float.parseFloat(s);
                } catch (final NumberFormatException e) {
                    return null;
                }
            }

            @Override
            public String toString(final Float f, final int flags) {
                return StringUtils.toString(f, SkriptConfig.numberAccuracy.value());
            }

            @Override
            public String toVariableNameString(final Float f) {
                return StringUtils.toString(f.doubleValue(), VARIABLENAME_NUMBERACCURACY);
            }

            @Override
            public String getVariableNamePattern() {
                return "-?\\d+(\\.\\d+)?";
            }
        }).serializer(new Serializer<Float>() {

            @Override
            public Fields serialize(final Float n) {
                // serialised natively by Yggdrasil
                throw new IllegalStateException();
            }

            @Override
            public boolean canBeInstantiated() {
                return true;
            }

            @Override
            public void deserialize(final Float o, final Fields f) throws StreamCorruptedException {
                assert false;
            }

            // return "" + f;
            @Override
            @Nullable
            public Float deserialize(final String s) {
                try {
                    return Float.parseFloat(s);
                } catch (final NumberFormatException e) {
                    return null;
                }
            }

            @Override
            public boolean mustSyncDeserialization() {
                return false;
            }
        }).math(Number.class, new NumberArithmetic()));
    }
    Classes.registerClass(new ClassInfo<>(Boolean.class, "boolean").user("booleans?").name("Boolean").description("A boolean is a value that is either true or false. Other accepted names are 'on' and 'yes' for true, and 'off' and 'no' for false.").usage("true/yes/on or false/no/off").examples("set {config.%player%.use mod} to false").since("1.0").parser(new Parser<Boolean>() {

        private final RegexMessage truePattern = new RegexMessage("boolean.true.pattern");

        private final RegexMessage falsePattern = new RegexMessage("boolean.false.pattern");

        private final Message trueName = new Message("boolean.true.name");

        private final Message falseName = new Message("boolean.false.name");

        @Override
        @Nullable
        public Boolean parse(final String s, final ParseContext context) {
            if (truePattern.matches(s))
                return Boolean.TRUE;
            if (falsePattern.matches(s))
                return Boolean.FALSE;
            return null;
        }

        @Override
        public String toString(final Boolean b, final int flags) {
            return (b ? trueName : falseName).toString();
        }

        @Override
        public String toVariableNameString(final Boolean b) {
            return "" + b;
        }

        @Override
        public String getVariableNamePattern() {
            return "(true|false)";
        }
    }).serializer(new Serializer<Boolean>() {

        @Override
        public Fields serialize(final Boolean n) {
            // serialised natively by Yggdrasil
            throw new IllegalStateException();
        }

        @Override
        public boolean canBeInstantiated() {
            return true;
        }

        @Override
        public void deserialize(final Boolean o, final Fields f) throws StreamCorruptedException {
            assert false;
        }

        // return "" + b;
        @Override
        @Nullable
        public Boolean deserialize(final String s) {
            if ("true".equals(s))
                return Boolean.TRUE;
            if ("false".equals(s))
                return Boolean.FALSE;
            assert false : s;
            return null;
        }

        @Override
        public boolean mustSyncDeserialization() {
            return false;
        }
    }));
    if (!DISABLE_BYTE_SHORT_FLOAT) {
        Classes.registerClass(new ClassInfo<>(Short.class, "short").name(ClassInfo.NO_DOC).defaultExpression(new SimpleLiteral<>((short) 1, true)).parser(new Parser<Short>() {

            @Override
            @Nullable
            public Short parse(final String s, final ParseContext context) {
                if (!SkriptParser.isInteger(s))
                    // Shorts are just limited integers
                    return null;
                try {
                    return Short.valueOf(s);
                } catch (final NumberFormatException e) {
                    return null;
                }
            }

            @Override
            public String toString(final Short s, final int flags) {
                return "" + s;
            }

            @Override
            public String toVariableNameString(final Short s) {
                return "" + s;
            }

            @Override
            public String getVariableNamePattern() {
                return "-?\\d+";
            }
        }).serializer(new Serializer<Short>() {

            @Override
            public Fields serialize(final Short n) {
                // serialised natively by Yggdrasil
                throw new IllegalStateException();
            }

            @Override
            public boolean canBeInstantiated() {
                return true;
            }

            @Override
            public void deserialize(final Short o, final Fields f) throws StreamCorruptedException {
                assert false;
            }

            // return "" + s;
            @Override
            @Nullable
            public Short deserialize(final String s) {
                try {
                    return Short.parseShort(s);
                } catch (final NumberFormatException e) {
                    return null;
                }
            }

            @Override
            public boolean mustSyncDeserialization() {
                return false;
            }
        }).math(Number.class, new NumberArithmetic()));
    }
    if (!DISABLE_BYTE_SHORT_FLOAT) {
        Classes.registerClass(new ClassInfo<>(Byte.class, "byte").name(ClassInfo.NO_DOC).defaultExpression(new SimpleLiteral<>((byte) 1, true)).parser(new Parser<Byte>() {

            @Override
            @Nullable
            public Byte parse(final String s, final ParseContext context) {
                try {
                    return Byte.valueOf(s);
                } catch (final NumberFormatException e) {
                    return null;
                }
            }

            @Override
            public String toString(final Byte b, final int flags) {
                return "" + b;
            }

            @Override
            public String toVariableNameString(final Byte b) {
                return "" + b;
            }

            @Override
            public String getVariableNamePattern() {
                return "-?\\d+";
            }
        }).serializer(new Serializer<Byte>() {

            @Override
            public Fields serialize(final Byte n) {
                // serialised natively by Yggdrasil
                throw new IllegalStateException();
            }

            @Override
            public boolean canBeInstantiated() {
                return true;
            }

            @Override
            public void deserialize(final Byte o, final Fields f) throws StreamCorruptedException {
                assert false;
            }

            // return "" + b;
            @Override
            @Nullable
            public Byte deserialize(final String s) {
                try {
                    return Byte.parseByte(s);
                } catch (final NumberFormatException e) {
                    return null;
                }
            }

            @Override
            public boolean mustSyncDeserialization() {
                return false;
            }
        }).math(Number.class, new NumberArithmetic()));
    }
    Classes.registerClass(new ClassInfo<>(String.class, "string").user("(text|string)s?").name("Text").description("Text is simply text, i.e. a sequence of characters, which can optionally contain expressions which will be replaced with a meaningful representation " + "(e.g. %player% will be replaced with the player's name).", "Because scripts are also text, you have to put text into double quotes to tell Skript which part of the line is an effect/expression and which part is the text.", "Please read the article on <a href='../strings/'>Texts and Variable Names</a> to learn more.").usage("simple: <code>\"...\"</code>", "quotes: <code>\"...\"\"...\"</code>", "expressions: <code>\"...%expression%...\"</code>", "percent signs: <code>\"...%%...\"</code>").examples("broadcast \"Hello World!\"", "message \"Hello %player%\"", "message \"The id of \"\"%type of tool%\"\" is %id of tool%.\"").since("1.0").parser(new Parser<String>() {

        @Override
        @Nullable
        public String parse(final String s, final ParseContext context) {
            switch(context) {
                case // in DEFAULT, parsing is handled by VariableString
                DEFAULT:
                    assert false;
                    return null;
                case // duh
                CONFIG:
                    return s;
                case SCRIPT:
                case EVENT:
                    if (VariableString.isQuotedCorrectly(s, true))
                        return Utils.replaceChatStyles(QUOTE_PATTERN_MATCHER.reset(s.substring(1, s.length() - 1)).replaceAll(Matcher.quoteReplacement("\"")));
                    return null;
                case COMMAND:
                    return s;
            }
            assert false;
            return null;
        }

        @Override
        public boolean canParse(final ParseContext context) {
            return context != ParseContext.DEFAULT;
        }

        @Override
        public String toString(final String s, final int flags) {
            return s;
        }

        @Override
        public String getDebugMessage(final String s) {
            return '"' + s + '"';
        }

        @Override
        public String toVariableNameString(final String s) {
            return s;
        }

        @Override
        public String getVariableNamePattern() {
            return ".*";
        }
    }).serializer(new Serializer<String>() {

        @Override
        public Fields serialize(final String n) {
            // serialised natively by Yggdrasil
            throw new IllegalStateException();
        }

        @Override
        public boolean canBeInstantiated() {
            return true;
        }

        @Override
        public void deserialize(final String o, final Fields f) throws StreamCorruptedException {
            assert false;
        }

        // return s;
        @Override
        public String deserialize(final String s) {
            return s;
        }

        @Override
        public boolean mustSyncDeserialization() {
            return false;
        }
    }));
/* Downgrades parser performance unnecessarily and generates bunch of illegal argument exceptions. But can be added in the future with a proper check.
        Classes.registerClass(new ClassInfo<>(UUID.class, "uuid").user("uuids?").parser(new Parser<UUID>() {
            public final @Nullable UUID parse(final String s, final ParseContext context) {
                try {
                    return UUID.fromString(s);
                } catch (final IllegalArgumentException ignored) {
                    // ignored
                }
                return null;
            }

            @SuppressWarnings("null")
            public final String toString(final UUID o, final int flags)
            {
                return o.toString();
            }

            @SuppressWarnings("null")
            public final String toVariableNameString(final UUID o)
            {
                return o.toString();
            }

            public final String getVariableNamePattern()
            {
                return ".+";
            }
        }).serializer(new Serializer<UUID>() {
            @Override
            public final Fields serialize(final UUID o) {
                final Fields f = new Fields();
                f.putObject("uuid", o);
                return f;
            }

            @Override
            public final void deserialize(final UUID o, final Fields f) throws StreamCorruptedException {
                throw new UnsupportedOperationException();
            }

            @SuppressWarnings("null")
            @Override
            protected final UUID deserialize(final Fields fields) throws StreamCorruptedException {
                return UUID.fromString((String)fields.getObject("uuid"));
            }

            @Override
            public final boolean mustSyncDeserialization() {
                return false;
            }

            @Override
            public final boolean canBeInstantiated(final Class<? extends UUID> clazz) {
                return false;
            }

            @Override
            protected final boolean canBeInstantiated() {
                return false;
            }
        }));
        */
}
Also used : NumberArithmetic(ch.njol.skript.classes.NumberArithmetic) RegexMessage(ch.njol.skript.localization.RegexMessage) Message(ch.njol.skript.localization.Message) VariableString(ch.njol.skript.lang.VariableString) StreamCorruptedException(java.io.StreamCorruptedException) Serializer(ch.njol.skript.classes.Serializer) Parser(ch.njol.skript.classes.Parser) SkriptParser(ch.njol.skript.lang.SkriptParser) Fields(ch.njol.yggdrasil.Fields) ParseContext(ch.njol.skript.lang.ParseContext) Nullable(org.eclipse.jdt.annotation.Nullable) RegexMessage(ch.njol.skript.localization.RegexMessage) ClassInfo(ch.njol.skript.classes.ClassInfo)

Example 5 with VariableString

use of ch.njol.skript.lang.VariableString in project LifeSkript by LifeMC.

the class Classes method toString.

private static final <T> String toString(@Nullable final T o, final StringMode mode, final int flags, @Nullable final VariableString variableName, final boolean debug) {
    assert flags == 0 || mode == StringMode.MESSAGE;
    if (o == null) {
        if (SkriptConfig.warnWhenUsingNoneValues.value() && mode != StringMode.DEBUG)
            if (variableName != null)
                Skript.warning("Usage of none is detected - the variable " + variableName + " is null (mode: " + mode + ", flags: " + flags + ", debug: " + debug + ')');
            else
                Skript.warning("Usage of none is detected - probably some variable or expression returned null (mode: " + mode + ", flags: " + flags + ')');
        return Language.get("none");
    }
    if (o.getClass().isArray()) {
        if (((Object[]) o).length == 0) {
            if (SkriptConfig.warnWhenUsingNoneValues.value() && mode != StringMode.DEBUG)
                if (variableName != null)
                    Skript.warning("Usage of none is detected - the variable " + variableName + " is empty (mode: " + mode + ", flags: " + flags + ", type: " + o.getClass().getCanonicalName() + ", debug: " + debug + ')');
                else
                    Skript.warning("Usage of none is detected - probably some list variable or expression is empty (mode: " + mode + ", flags: " + flags + ", type: " + o.getClass().getCanonicalName() + ')');
            return Language.get("none");
        }
        final StringBuilder b = new StringBuilder(4096);
        boolean first = true;
        for (final Object i : (Object[]) o) {
            if (!first)
                b.append(", ");
            b.append(toString(i, mode, flags, null, false));
            first = false;
        }
        return "[" + b + ']';
    }
    for (final ClassInfo<?> ci : classInfos) {
        final Parser<?> parser = ci.getParser();
        if (parser != null && ci.getC().isInstance(o)) {
            @SuppressWarnings("unchecked") final String s = mode == StringMode.MESSAGE ? ((Parser<T>) parser).toString(o, flags) : mode == StringMode.DEBUG ? '[' + ci.getCodeName() + ':' + ((Parser<T>) parser).toString(o, mode) + ']' : ((Parser<T>) parser).toString(o, mode);
            return s;
        }
    }
    return (mode == StringMode.VARIABLE_NAME ? "object:" : "") + o;
}
Also used : VariableString(ch.njol.skript.lang.VariableString) Parser(ch.njol.skript.classes.Parser)

Aggregations

VariableString (ch.njol.skript.lang.VariableString)7 Parser (ch.njol.skript.classes.Parser)3 List (java.util.List)3 Skript (ch.njol.skript.Skript)2 ClassInfo (ch.njol.skript.classes.ClassInfo)2 SectionNode (ch.njol.skript.config.SectionNode)2 ExprColoured (ch.njol.skript.expressions.ExprColoured)2 Effect (ch.njol.skript.lang.Effect)2 ExpressionList (ch.njol.skript.lang.ExpressionList)2 ParseContext (ch.njol.skript.lang.ParseContext)2 SkriptParser (ch.njol.skript.lang.SkriptParser)2 Message (ch.njol.skript.localization.Message)2 Classes (ch.njol.skript.registrations.Classes)2 CommandSender (org.bukkit.command.CommandSender)2 Event (org.bukkit.event.Event)2 Nullable (org.eclipse.jdt.annotation.Nullable)2 ScriptLoader (ch.njol.skript.ScriptLoader)1 SkriptConfig (ch.njol.skript.SkriptConfig)1 NumberArithmetic (ch.njol.skript.classes.NumberArithmetic)1 Serializer (ch.njol.skript.classes.Serializer)1