The CODEBLOCK type was introduced in the XBase language in the Clipper days.
They can be viewed as unnamed functions. They can have 0 or more parameters and return a value.
The most simple codeblock that returns a string literal looks like this:
FUNCTION Start() AS VOID
LOCAL cb AS CODEBLOCK
cb := {|| "Hello World"}
? Eval(cb)
WAIT
RETURN
To use a codeblock, you call the Eval() runtime function.
Codeblocks are not restricted to fixed expressions, because they can use parameters.
The following codeblock adds two parameters:
FUNCTION Start() AS VOID
LOCAL cb AS CODEBLOCK
cb := {|a,b| a + b}
? Eval(cb, 1,2)
? Eval(cb, "Helllo ", "World")
WAIT
RETURN
As you can see in the example, both numeric or string parameters can be used here and work. That is because the parameters to a codeblock are of the so called USUAL type; they can contain any value. Of course the following will fail because the USUAL type does not support multiplying strings:
FUNCTION Start() AS VOID
LOCAL cb AS CODEBLOCK
cb := {|a,b| a * b}
? Eval(cb, 1,2)
? Eval(cb, "Helllo ", "World")
WAIT
RETURN
Codeblocks are not restricted to single expressions.
They may also contain a (comma-separated) list of expressions. The value of the last expression is the return value of the codeblock:
FUNCTION Start() AS VOID
LOCAL cb AS CODEBLOCK
cb := {|a,b,c| QOut("value 1", a) , QOut("value 2", b), QOut("value 3", c), a*b*c}
? Eval(cb,10,20,30)
WAIT
RETURN
XSharp has also introduced codeblocks that contain of (lists of) statements:
FUNCTION Start() AS VOID
LOCAL cb AS CODEBLOCK
cb := {| a,b,c|
? "value 1" ,a
? "value 2" ,b
? "value 3" ,c
RETURN a*b*c
}
? Eval(cb,10,20,30)
WAIT
RETURN
•The first statement should start on a new line after the parameter list.
•There should be NO semicolon after the parameter list.
•The statement list should end with a RETURN statement.
The CODEBLOCK type is implemented in the abstract class XSharp.Codeblock.
The Usualtype of CODEBLOCK has the value 9.
In your code you will never have objects of type XSharp.Codeblock.
Compile time codeblocks are translated into a subclass of XSharp.Codeblock.
Runtime (macro compiled) codeblocks are translated into a subclass of the class XSharp._Codeblock, which inherits from Codeblock.
Depending on the type of the runtime codeblock, this is either an instance of the MacroCodeblock class or of the MacroMemVarCodeblock class (when the macro creates dynamic memory variables).