Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a function pointer or array of functions in PowerShell?

I would like to do something like this. Index into an array of functions and apply the appropriate function for the desired loop index.

for ($i = 0; $i -lt 9; $i++)
{
    $Fields[$i] = $Fields[$i] | $($FunctionTable[$i])
}
#F1..F9 are defined functions or rather filter functions

$FunctionTable =  {F1}, 
                {F2}, 
                {F3},
                {F4},
                {F5},
                {F6},
                {F7},
                {F8},
                {F9}
like image 944
tellingmachine Avatar asked Jul 07 '09 20:07

tellingmachine


People also ask

Does powershell have pointers?

Powershell provides also the ability to use function pointers such as C or C++.

Can we have an array of function pointers?

4) Like normal pointers, we can have an array of function pointers. Below example in point 5 shows syntax for array of pointers.

What is array of function pointer?

Array of Function PointersWe declare and define four functions which take two integer arguments and return an integer value. These functions add, subtract, multiply and divide the two arguments regarding which function is being called by the user.

Is function pointer and function pointer same?

A function pointer, also called a subroutine pointer or procedure pointer, is a pointer that points to a function. As opposed to referencing a data value, a function pointer points to executable code within memory.


2 Answers

Here's an example of how to do this using the call (&) operator.

# define 3 functions
function a { "a" }
function b { "b" }
function c { "c" }

# create array of 3 functioninfo objects
$list = @(
  (gi function:a),
  (gi function:b),
  (gi function:c)
)

0, 1, 2 | foreach {
  # call functions at index 0, 1 and 2
  & $list[$_]
}

-Oisin

p.s. this means your pipeline should bve amended to something like:

$Fields[$i] = $Fields[$i] | & $FunctionTable[$i]
like image 90
x0n Avatar answered Sep 20 '22 00:09

x0n


Here is something similar also using the & operator:

function f1
{ "Exec f1" }

function f2
{ "Exec f2" }

function f3
{ "Exec f3" }

function f4
{ "Exec f4" }

function UseFunctionList ( [string[]]$FunctionList )  
{  
foreach ( $functionName in $functionList )  
  {
  & $FunctionName
  }
}

function Go  
{  
'List 1'  
$FunctionList = 'f1','f2','f3','f4'  
UseFunctionList $FunctionList  
'List 2'  
$FunctionList = 'f4','f3','f2'  
UseFunctionList $FunctionList  
}

like image 23
David Mans Avatar answered Sep 22 '22 00:09

David Mans