User-inputed code/math

BlitzMax Forums/BlitzMax Beginners Area/User-inputed code/math

The forum is locked. These are the original blitzbasic.com forums, kept so they can still be read. No new topics, replies or edits can be made here. To join in, head over to the Blitz3D+ forums.

Your have to parse it yourself im afraid.

Either parsing/evaluating directly. or producing a parse tree, and evaluate that.

EDIT:
i was bored so i whipped up a simple expression evaluator as an example =)

EDIT2: beefed up version of this in code archives Expression Evaluator

Global source:String
Global pos:Int

Function ReportError( s:String)
	Print "ERROR: pos="+pos+" : "+s
EndFunction

Function EatWhitespace()
	While source[pos] = Asc(" ") 
		pos :+ 1
	Wend
EndFunction

Function EatNumber:Float()
	Local start:Int = pos
	Local gotsep:Int = False
	Local res:String	
	While (source[pos] >= Asc("0")) And (source[pos] <= Asc("9"))
		pos :+ 1
		If source[pos] = Asc(".") Then
			If gotsep Then ReportError( "error in float number")
			gotsep = True
			pos :+ 1
		EndIf
	Wend
	Return source[start..pos].ToFloat()
EndFunction

Function Primary:Float()
	Local lvalue:Float
	EatWhitespace()
	If source[pos] = Asc("(") Then
		pos :+ 1
		lvalue = AddExpression()
    		If source[pos] <> Asc(")") Then ReportError( "expected )")
    		pos :+ 1
	ElseIf (source[pos] >= Asc("0")) And (source[pos] <= Asc("9")) Then
		lvalue = EatNumber()
	ElseIf source[pos] = Asc("-") Then
		pos :+ 1
		lvalue = - Primary()
	Else
		ReportError( "expected number or -number or (expression)")
	EndIf
	EatWhitespace()
	Return lvalue
EndFunction

Function MulExpression:Float()
	Local lvalue:Float, rvalue:Float
	EatWhitespace()
	lvalue = Primary()
	While (source[pos] = Asc("*")) Or (source[pos] = Asc("/"))
		If source[pos] = Asc("*") Then
			pos :+ 1
			rvalue = Primary()
			lvalue = lvalue * rvalue
		ElseIf source[pos] = Asc("/") Then
			pos :+ 1
			rvalue = Primary()
			lvalue = lvalue / rvalue
		EndIf
	Wend
	EatWhitespace()
	Return lvalue
EndFunction
	
Function AddExpression:Float()
	Local lvalue:Float, rvalue:Float
	EatWhitespace()
	lvalue = MulExpression()
	While (source[pos] = Asc("+")) Or (source[pos] = Asc("-")) 
		If source[pos] = Asc("+") Then
			pos :+ 1
			rvalue = MulExpression()
			lvalue = lvalue + rvalue
		ElseIf source[pos] = Asc("-") Then
			pos :+ 1
			rvalue = MulExpression()
			lvalue = lvalue - rvalue		
		EndIf
	Wend
	EatWhitespace()
	Return lvalue
EndFunction

Function Expression:Float( s:String)
	Local result:Float
	source = s.Trim()
	pos = 0
	result = AddExpression()
	If pos < source.Length Then 
		ReportError( "invalid expression")
		Return 0
	EndIf
	Return result	
EndFunction

Print "3*5+3.2/7 = " + (3*5+3.2/7)
Print "expression= " + Expression( "3 * 5 + 3.2 / 7")