Dynamic Evaluation

Sometimes it can be useful to run Lucee code which has been dynamically generated, or access variables which are dynamically generated. This can enable meta programming when the code or variable names cannot be known at compile time.

Dynamic Variables

The following code sets a dynamic variable "test"

Loading gist https://gist.github.com/roryl/95f6bd166627abb425a4.json, file: dynamic_variable.cfm...

Its also possible to use the getVariable() function to dynamically evaluate a variable name:

Loading gist https://gist.github.com/roryl/95f6bd166627abb425a4.json, file: get_variable.cfm...

Evaluate

When doing more complex dynamic evaluations, you can make use of the evalute() function which will execute any Lucee expression as if it was normally executed. This example below produces the same output as above.

Loading gist https://gist.github.com/roryl/95f6bd166627abb425a4.json, file: evaluate.cfm...

Dynamic Struct Array Notation

It is also possibly to dynamically access the members of a structure using array notation

Loading gist https://gist.github.com/roryl/95f6bd166627abb425a4.json, file: dynamic_struct_keys.cfm...

Dynamic Lucee Code

Dynamically running Lucee tags or script that is more complex than simple expressions is usually not possible with evaluate(). In these situations, we can make use of Lucee's virtual filesystem to write and include dynamic code.

First it is necessary to create a mapping to the virtual file system. The mapping can be named anything, in this example it is named temp

Loading gist https://gist.github.com/roryl/95f6bd166627abb425a4.json, file: Application.cfc...

Then it is possible to dynamically create .cfm templates and include them. This example below compiles a template that outputs the time with a 50 milisecond delay, based on the number of iterations specified.

Loading gist https://gist.github.com/roryl/95f6bd166627abb425a4.json, file: dynamic_compilation.cfm...

ArgumentCollection

It is possible to pass to functions a dynamic set of arguments. This is useful when forwarding arguments from one function to another, or where there are a lot of arguments that need to be prepared.

Loading gist https://gist.github.com/roryl/95f6bd166627abb425a4.json, file: argument_collection.cfm...

When executing this example, it results in:

17
17

results matching ""

    No results matching ""