Dynamic Variable Instantiation

6 Apr 2016: A “SetVarByName” custom function can make things a whole lot easier. For details, see Set Variable by Name.

31 Oct 2014: This was originally embedded inside another article, but I now realize it should have been a standalone post, so I am belatedly taking corrective action and making it so.

Although FileMaker provides a “Set Field By Name” script step, it does not provide a direct method to dynamically declare the name of a variable.

dvi

Note that I said there isn’t a “direct” method to accomplish this… but it can be done indirectly.

Creating Variables on the Fly

There’s something cool and slightly miraculous about being able to dynamically name and populate variables at runtime. In the code below we don’t care about $x at all — it’s just a convenient way to access the calculation engine so we can invoke the Evaluate and Let functions.

We’ll come back to that in a minute, but first let’s consider a much simpler example. If we know the name of the variable we want to declare, but want to specify the repetition dynamically, it can be accomplished in a very straight-forward manner, like so:

non-dynamic variable instantiation

This gives us a variable named $array_01[x] where “x” represents whatever number is currently in the $rep variable.

The following also achieves the same result, but normally we wouldn’t bother since it’s more work with no additional benefit. But it does show that a variable can be defined via Let, with the rep specified dynamically — in this example, via a variable, $rep, but Get(RecordNumber) or any calculated expression would work.

However, the technique breaks down if we try to dynamically specify the name of the variable itself. In the above example, we’re telling FileMaker to define a variable named $array_01 with whatever repetition number happens to be sitting in the $rep variable.

But we want to declare a variable named $array_xx where “xx” could be anything from “00” to “12” and is based on the value sitting in the $column variable (padded with a leading zero where appropriate), and to pull that off we need to bring out the heavy artillery, i.e., Evaluate.

It makes my head hurt, but it actually works.

One thought on “Dynamic Variable Instantiation

  1. Kevin Frank Post author

    If you prefer, an alternative to the \"\" at the end of the code snippet above, is to use $null instead — provided of course that $null is empty.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s