Page 1 of 1

excecute code at runtime

Posted: Sat Sep 24, 2011 3:21 pm
by t57042
Is this somehow possible in Pb?

a$="5+3"

debug @a$ ---> result printed is 8

Richard

Re: excecute code at runtime

Posted: Sat Sep 24, 2011 3:36 pm
by RASHAD
Hi

Code: Select all

Dim b$(2)

a$ = "15 + 22"

For i = 1 To 2
  b$(i) =  StringField(a$,i,"+")
Next

Debug ValF(b$(1)) + ValF(b$(2))

Re: excecute code at runtime

Posted: Sat Sep 24, 2011 3:51 pm
by Arctic Fox
An expression evaluator might do the job.
http://www.purebasic.fr/english/viewtop ... 12&t=18359

Re: excecute code at runtime

Posted: Sat Sep 24, 2011 4:53 pm
by Kiffi

Code: Select all

UseSQLiteDatabase()
OpenDatabase(0, ":memory:", "", "", #PB_Database_SQLite)
DatabaseQuery(0, "Select 5+3")
NextDatabaseRow(0)
Debug GetDatabaseString(0, 0) ;  ---> result printed is 8
CloseDatabase(0)
Greetings ... Kiffi

Re: excecute code at runtime

Posted: Sat Sep 24, 2011 5:08 pm
by MachineCode
Nice, Kiffi... but kinda useless without float results ("22/7").

Also, very bloated... the 6 lines of code create a 403 KB executable. :shock:

But I guess if your app has database code anyway, then it's a good hack for non-float calculations.

Re: excecute code at runtime

Posted: Sat Sep 24, 2011 5:38 pm
by t57042
Why does the sqlite way not work with floats?

Re: excecute code at runtime

Posted: Sat Sep 24, 2011 5:40 pm
by skywalk
Very nice Kiffi :)
@MachineCode -

Code: Select all

UseSQLiteDatabase()
OpenDatabase(0, ":memory:", "", "", #PB_Database_SQLite)
DatabaseQuery(0, "Select round(22.0/7.0,2)")
NextDatabaseRow(0)
Debug GetDatabaseString(0, 0) ;--> 3.14
CloseDatabase(0)

Re: excecute code at runtime

Posted: Sat Sep 24, 2011 5:44 pm
by MachineCode
Thanks, SkyWalk!

Re: excecute code at runtime

Posted: Sun Sep 25, 2011 12:22 am
by Danilo
Another include for this: Evaluate() - Expression Parser

Supports the following operators:
+, -, *, /, % (modulo), ^ (power of), <<, >>, =, <>, <, >, <=, =<, >=, =>, ( ) , &, |, !, ~, NOT, OR, AND, XOR

- Integer
- Floats (1E5, 123.5e-20 etc.)
- add variables, for example EvaluateVariables("pi") = StrD(#PI,1000)
- Hex-Format ($FFFF, $abc)
- Bin-Format (%01010101)
- Errorhandler: SetEvaluateErrorHandler(@myErrorHandler())

Example:

Code: Select all

XIncludeFile "Evaluate.pbi"

Debug Evaluate("10 + 4 * 2")
Example with variables:

Code: Select all

XIncludeFile "Evaluate.pbi"

EvaluateVariables("n") = "64"
EvaluateVariables("f") = "0.25"

Debug Evaluate("n * f")

EDIT:
Download include with 2 examples: EvaluateExpression.zip (8,5k)

EDIT2:
Removed the need for #GENERATE_STACKMACHINE_ASM by using "CompilerIf Defined()"
Download again, EvaluateExpression.zip (8,5k)

EDIT3:
changed *start to *evaluateStart and variables in procedures from Define to Protected
Download again, EvaluateExpression.zip (8,5k)