Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/main/java/net/objecthunter/exp4j/Expression.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ public class Expression {

private final Map<String, Double> variables;

private VariableProvider variableProvider;

private final Set<String> userFunctionNames;

private static Map<String, Double> createDefaultVariables() {
Expand Down Expand Up @@ -71,6 +73,10 @@ public Expression setVariable(final String name, final double value) {
return this;
}

public void setVariableProvider(final VariableProvider variableProvider) {
this.variableProvider = variableProvider;
}

private void checkVariableName(String name) {
if (this.userFunctionNames.contains(name) || Functions.getBuiltinFunction(name) != null) {
throw new IllegalArgumentException("The variable name '" + name + "' is invalid. Since there exists a function with the same name");
Expand Down Expand Up @@ -172,7 +178,10 @@ public double evaluate() {
output.push(((NumberToken) t).getValue());
} else if (t.getType() == Token.TOKEN_VARIABLE) {
final String name = ((VariableToken) t).getName();
final Double value = this.variables.get(name);
Double value = this.variables.get(name);
if (value == null && variableProvider != null) {
value = variableProvider.getVariable(name);
}
if (value == null) {
throw new IllegalArgumentException("No value has been set for the setVariable '" + name + "'.");
}
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/net/objecthunter/exp4j/VariableProvider.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package net.objecthunter.exp4j;

public interface VariableProvider {
Double getVariable(String variable);
}