|
| 1 | +package io.github.syst3ms.skriptparser.expressions; |
| 2 | + |
| 3 | +import io.github.syst3ms.skriptparser.Parser; |
| 4 | +import io.github.syst3ms.skriptparser.lang.Expression; |
| 5 | +import io.github.syst3ms.skriptparser.lang.TriggerContext; |
| 6 | +import io.github.syst3ms.skriptparser.lang.Variable; |
| 7 | +import io.github.syst3ms.skriptparser.log.ErrorType; |
| 8 | +import io.github.syst3ms.skriptparser.parsing.ParseContext; |
| 9 | +import org.jetbrains.annotations.Nullable; |
| 10 | + |
| 11 | +import java.util.Map; |
| 12 | + |
| 13 | +/** |
| 14 | + * All indices of a given list variable. |
| 15 | + * |
| 16 | + * @name Indices of List |
| 17 | + * @type EXPRESSION |
| 18 | + * @pattern [all [of] [the]] ind(exes|ices) of %^objects% |
| 19 | + * @since ALPHA |
| 20 | + * @author Mwexim |
| 21 | + */ |
| 22 | +public class ExprVariableIndices implements Expression<String> { |
| 23 | + static { |
| 24 | + Parser.getMainRegistration().addExpression( |
| 25 | + ExprVariableIndices.class, |
| 26 | + String.class, |
| 27 | + false, |
| 28 | + "[all [of] [the]] ind(exes|ices) of %^objects%" |
| 29 | + ); |
| 30 | + } |
| 31 | + |
| 32 | + private Variable<Object> value; |
| 33 | + |
| 34 | + @SuppressWarnings("unchecked") |
| 35 | + @Override |
| 36 | + public boolean init(Expression<?>[] expressions, int matchedPattern, ParseContext parseContext) { |
| 37 | + value = (Variable<Object>) expressions[0]; |
| 38 | + if (value.isSingle()) { |
| 39 | + var logger = parseContext.getLogger(); |
| 40 | + logger.error( |
| 41 | + "Only list variables are allowed, found '" + value.toString(TriggerContext.DUMMY, logger.isDebug()) + "'", |
| 42 | + ErrorType.SEMANTIC_ERROR |
| 43 | + ); |
| 44 | + return false; |
| 45 | + } |
| 46 | + return true; |
| 47 | + } |
| 48 | + |
| 49 | + @SuppressWarnings("unchecked") |
| 50 | + @Override |
| 51 | + public String[] getValues(TriggerContext ctx) { |
| 52 | + return value.getRaw(ctx) |
| 53 | + .map(val -> (Map<String, Object>) val) // We know for a fact it is a list variable |
| 54 | + .map(val -> val.keySet().toArray(new String[0])) |
| 55 | + .orElse(new String[0]); |
| 56 | + |
| 57 | + } |
| 58 | + |
| 59 | + @Override |
| 60 | + public String toString(@Nullable TriggerContext ctx, boolean debug) { |
| 61 | + return "indices of " + value.toString(ctx, debug); |
| 62 | + } |
| 63 | +} |
0 commit comments