Mega Code Archive

 
Categories / Delphi / Examples
 

Calling a Procedure with its name in a variable

Title: Calling a Procedure with it's name in a variable Question: How can I call a procedure whose name comes from a table, list, etc.? In other words, based on the environment I want to load a procedure name into a variable and call it. What would be the instruction? Answer: The following code will allow us to save a list of procedures that we can call later. unit uProcDict; interface type MyProc = procedure(s: string); procedure RegisterProc(procName: string; proc: MyProc); procedure ExecuteProc(procName: string; arg: string); implementation uses Classes; var ProcDict: TStringList; procedure RegisterProc(procName: string; proc: MyProc); begin ProcDict.AddObject(procName, TObject(@proc)); end; procedure ExecuteProc(procName: string; arg: string); var index: Integer; begin index := ProcDict.IndexOf(ProcName); if index = 0 then MyProc(ProcDict.objects[index])(arg); // Missing error reporting end; initialization ProcDict := TStringList.Create; ProcDict.Sorted := true; finalization ProcDict.Free; end.