User Guide > Scripting > Setting the Scope of Functions
Was this helpful?
Setting the Scope of Functions
To define a function available to an entire process, use the Public keyword:
Public Function xyzzy()
xyzzy="xyzzy"
End Function
Substitute the Private keyword to create a function available only to the transformation or process. Or use Dim to create a function only available in the current function module.
Caution!  Directly referencing variables: Within a function you should not directly reference a variable declared at a lower (more restrictive scope) than the function itself. This means a Public function should not directly reference Private or module-scoped variables, and a Private function should not directly reference module-scoped variables. Either pass the variable to function as a parameter, or change the scoping of the variable (or the function).

Due to the way the runtime references variables, trying to reference a variable at a lower scope than the function could result in the wrong variable being referenced. If the function only gets compiled once this will not be a problem, but if it gets compiled more than once (i.e. if a code library is included in two transformations in a process) the wrong variable is likely to be referenced sometimes. The compiler does not flag this as an error both for legacy reasons (a public function referencing a private variable was not a problem when public and private were the same scope), and because the compiler cannot detect the cases where this will result in the wrong variable being referenced.
Functions and local variables can be instantiated implicitly, just by using them, though this does produce some potential problems, as follows:
Function foo()
b = 3
...
End Function
b = 2
foo()
The variable b in function foo() is local to the function, and later comes into existence as a private variable. This works as it should, but could be confusing. To get around this, the Dim statement is supported (though in a restricted form, compared to Visual Basic).
Dim b
Function foo()
b = 3
...
End Function
b = 2
foo()
After the function call, b contains 3, as expected.
To declare a private variable, just use Private in place of Dim. Once you define a public function, it can be used anywhere you can use a function.
Best Practice — When debugging expressions, it is important to test functions before using them in other fields.
Last modified date: 10/22/2024