Created
February 4, 2022 16:34
-
-
Save boxbeam/6a3c36997c6c79f5ad84ee9c9ea47dd0 to your computer and use it in GitHub Desktop.
A simple snippet that allows you to compile a Crunch expression that uses PlaceholderAPI placeholders.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package redempt.test; | |
import me.clip.placeholderapi.PlaceholderAPIPlugin; | |
import me.clip.placeholderapi.expansion.PlaceholderExpansion; | |
import me.clip.placeholderapi.expansion.manager.LocalExpansionManager; | |
import org.bukkit.entity.Player; | |
import redempt.crunch.CompiledExpression; | |
import redempt.crunch.Crunch; | |
import redempt.crunch.data.FastNumberParsing; | |
import redempt.crunch.functional.EvaluationEnvironment; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
public class PlaceholderExpression { | |
private static Pattern placeholderPattern = Pattern.compile("%([^% ]+)_([^% ]+)%"); | |
private CompiledExpression exp; | |
private Player player; | |
public PlaceholderExpression(String str, EvaluationEnvironment env) { | |
Matcher matcher = placeholderPattern.matcher(str); | |
LocalExpansionManager manager = PlaceholderAPIPlugin.getInstance().getLocalExpansionManager(); | |
while (matcher.find()) { | |
String placeholder = matcher.group(); | |
String identifier = matcher.group(1); | |
String arg = matcher.group(2); | |
PlaceholderExpansion expansion = manager.getExpansion(identifier); | |
if (expansion == null) { | |
continue; | |
} | |
env.addLazyVariable(placeholder, () -> { | |
String replaced = expansion.onRequest(player, arg); | |
if (replaced == null) { | |
return 0; | |
} | |
return FastNumberParsing.parseDouble(replaced); | |
}); | |
} | |
exp = Crunch.compileExpression(str, env); | |
} | |
public PlaceholderExpression(String str) { | |
this(str, new EvaluationEnvironment()); | |
} | |
public double evaluate(Player player) { | |
this.player = player; | |
return exp.evaluate(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment