improve: UserValue API

This commit is contained in:
TopchetoEU 2024-12-28 13:20:04 +02:00
parent 9ce0504948
commit b97e4bf163
Signed by: topchetoeu
GPG Key ID: 6531B8583E5F6ED4
2 changed files with 10 additions and 3 deletions

View File

@ -32,16 +32,17 @@ public class Arguments {
public Value self() { public Value self() {
return get(-1); return get(-1);
} }
@SuppressWarnings("unchecked")
public <T> T self(Class<T> clazz) { public <T> T self(Class<T> clazz) {
if (self instanceof UserValue user && clazz.isInstance(user.value)) return (T)user.value; return UserValue.unwrap(clazz, self);
else return null;
} }
public Value get(int i) { public Value get(int i) {
if (i >= args.length || i < -1) return Value.UNDEFINED; if (i >= args.length || i < -1) return Value.UNDEFINED;
else if (i == -1) return self; else if (i == -1) return self;
else return args[i]; else return args[i];
} }
public <T> T get(Class<T> clazz, int i) {
return UserValue.unwrap(clazz, get(i));
}
public Value getOrDefault(int i, Value def) { public Value getOrDefault(int i, Value def) {
if (i < -1 || i >= args.length) return def; if (i < -1 || i >= args.length) return def;
else return get(i); else return get(i);

View File

@ -77,4 +77,10 @@ public final class UserValue<T> extends Value {
public static <T> UserValue<T> of(T value, ObjectValue prototype) { public static <T> UserValue<T> of(T value, ObjectValue prototype) {
return new UserValue<T>(value, prototype); return new UserValue<T>(value, prototype);
} }
@SuppressWarnings("unchecked")
public static <T> T unwrap(Class<T> clazz, Value val) {
if (val instanceof UserValue user && clazz.isInstance(user.value)) return (T)user.value;
else return null;
}
} }