Jump to content
  • Advertisement
Sign in to follow this  
  • entries
  • comments
  • views

VB code dom expression evaluator

Sign in to follow this  


The following uses the codedom to compile and execute vb expressions on the fly. Thought I'd share.

Module Module1

Sub Main()
Dim Expressions() As String = {"2*args(0)+3*args(1) <= 20", "5*args(1)+7*args(0) < 10", "6*args(0)+2*args(1) < 50"}
Dim c As New ExpressionEvaluator
Dim AllTrue As Boolean = True

Dim X As Integer = 0
Dim Y As Integer = 1

For Each expression As String In Expressions
AllTrue = AllTrue And c.EvaluateExpression(expression, X, Y)

If AllTrue Then
Console.WriteLine("All expressions are true")
End If
End Sub

End Module

Class ExpressionEvaluator

Private Compiler As CodeDom.Compiler.ICodeCompiler
Sub New()
Dim c As New Microsoft.VisualBasic.VBCodeProvider
Compiler = c.CreateCompiler
End Sub

'evaluates an expression and returns the result
Public Function EvaluateExpression(ByVal Expression As String, ByVal ParamArray args() As Object) As Object
Dim results As CodeDom.Compiler.CompilerResults
results = Compiler.CompileAssemblyFromSource(CompilerParameters, CreateSource(Expression))
If results.Errors.Count > 0 Then
Dim ExMessage As String
For Each e As CodeDom.Compiler.CompilerError In results.Errors
ExMessage &= "Error " & e.ErrorNumber & " at " & e.Line & ": " & e.ErrorText & vbNewLine
Throw New Exception("Errors were found while compiling: " & vbNewLine & ExMessage)
End If
If args Is Nothing Then
args = New Object() {}
End If
Return results.CompiledAssembly.GetType("Module1").InvokeMember("Foo", Reflection.BindingFlags.InvokeMethod, Nothing, Nothing, args, Nothing, Nothing, Nothing)
End Function

Private Function CreateSource(ByVal expression As String) As String
Return "Public Module Module1" & vbNewLine & _
"Function Foo(ByVal Paramarray args() as object) as object" & vbNewLine & _
"Return " & expression & vbNewLine & _
"End Function" & vbNewLine & _
"End Module"
End Function

Private Function CompilerParameters() As CodeDom.Compiler.CompilerParameters
Dim parameters As New CodeDom.Compiler.CompilerParameters
parameters.CompilerOptions = "/t:library"
parameters.GenerateInMemory = True
Return parameters
End Function
End Class

In other news, having a cold on the fourth sucks.
Sign in to follow this  


Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!