March 11, 2022

AHK Conditional include

I share here some learning how to bypass "call to non-existent function" error to make dependencies optional.

Problem description

I faced the following challenge in AutoHotkey:
I had a function calling some Library.
What I wanted it to skip the feature if the required library was not included i.e. make the library dependency optional.

Unfortunately, just wrapping the code block between a IsFunc block, still triggered the "call to non-existent function" error at first run.

Solution

I have found the solution in this old post: https://www.autohotkey.com/board/topic/34194-how-to-handle-the-error-call-to-non-existent-function/ , answer by SKAN (thanks).

To workaround the check/ by-pass the error you can call the function dynamically, that is if you want to call the function with the name FunName, call it like this %FunName%(...)

You can then wrap the whole between a If IsFunc or If FileExist("Lib/LibName.ahk") block  (for library calling a subfunction in a library in the same Lib folder).

Example in People Lib for removing hard dependency to the Connections Lib:


If FileExist("Lib/Connections.ahk") {
FunStr := "Connections_Profile2Email"
...
    sEmail := %FunStr%(sMatch)
    ...
}
} ; end if Lib exists

Unfortunately, the function dynamically called is here not recognized: you have to include the Lib explicitly :-(

To work around this I have implemented this function (I got the idea from here - GitHub user davebrny) include_cond.ahk

To use it, in your main script in the auto-execute portion call include_cond("Lib1, Lib2")
Right after, include the file  ~ScriptName_includes.ahk
(replace ScriptName by the main Script name) 
This file will be generated by include_cond.

Note: this has no sense to use this for the compiled version.

At the first run, if this file is not provided you will get an error at the include line.
This is the main drawback: you have to provide an empty  ~ScriptName_includes.ahk along your main script to have it run from scratch.

But still, this way your main script will run even if some libraries are removed/ not available.

See also

How to handle the error: call to non-existent function - Ask for Help - AutoHotkey Community

Check if Func( ) exists : AutoHotkey - Reddit

(autohotkey) - create a list of .ahk files to be #included in your main script

No comments:

Post a Comment