routine_id

Definition: integer rid = routine_id(string st)
Description: Return an integer id number, known as a routine id , for a user-defined procedure or function.
The name of the procedure or function is given by the string sequence st.
-1 is returned if the named routine cannot be found.
Comments: The id number can be passed to call_proc() or call_func(), to indirectly call the routine named by st.

The routine named by st must be visible, i.e. callable, at the place where routine_id() is used to get the id number. Indirect calls to the routine can appear earlier in the program than the definition of the routine, but the id number can only be obtained in code that comes after the definition of the routine - see example 2 below.

Once obtained, a valid routine id can be used at any place in the program to call a routine indirectly via call_proc()/call_func().
Some typical uses of routine_id() are:
1. Creating a subroutine that takes another routine as a parameter. (See Example 2 below)
2. Setting up an Object-Oriented system.
3. Defining a call_back(). (See Calling C Functions)

Note that C routines, callable by Phix, also have routine ids. See define_c_proc() and define_c_func().
Example 1:
procedure foo()
    puts(1, "Hello World\n")
end procedure
constant r_foo_num = routine_id("foo")
call_proc(r_foo_num, {})    -- same as calling foo()
Example 2:
function apply_to_all(sequence s, integer f)
-- apply a specified function to all elements of a sequence
sequence result = {}
    for i=1 to length(s) do
        -- we can call add1() here, even if it is not in scope
        result = append(result, call_func(f, {s[i]}))
    end for
    return result
end function

function add1(atom x)
-- (this may be a private function in a different file)
    return x + 1
end function

? apply_to_all({1, 2, 3}, routine_id("add1"))  -- displays {2,3,4}

Note that add1 could be a private function in a completely different file; there is no need for it to be in scope when called.
See Also: call_proc, call_func, call_back, define_c_func, define_c_proc, Calling C Functions