Check script code without running it, and report its errors and warnings.
These functions are exported by the KS module.
Result := ValidateScript(Code) Result := CompileScript(Code)
Type: String
Either the path of a script file or the script source itself. If a file of that name exists it is checked, otherwise the value is checked as source.
Type: Object
Both functions return an object with these properties:
| Property | Description |
|---|---|
IsValid | 1 if no errors were found, otherwise 0. |
Errors | An Array of error messages, empty when IsValid is 1. |
Warnings | An Array of warning messages. Always empty for ValidateScript. |
A ValidateScript message is prefixed with its location where that is known: the file when Code names one, then the line and column, as in C:\Scripts\other.ks:3:7: message.
CompileScript splits the compiler's own report into lines, one line per element, so its Arrays also contain the report's heading lines, such as The following errors occurred:. When compilation fails, Errors can also contain the report's warning lines.
| ValidateScript | CompileScript | |
|---|---|---|
| What it checks | Syntax: the script is parsed. | Everything a build checks: the script is parsed, lowered and compiled in memory, so errors in inline C# and in the generated code are reported too. |
| Component needed | The parser | The compiler |
| Command-line equivalent | --validate-syntax | --validate |
An Error is thrown if the component the function needs is not installed. Use IsComponentAvailable when the component is optional at run time. Errors in the checked code are reported in the returned object.
Neither function runs the code: no hotkeys are registered and the auto-execute section does not run. CompileScript writes nothing to disk and does not restore packages, so a #Package the code names must already be available.
A compiled script with a statically visible call to either function includes the component it needs; see Optional Scripting Components.
Compiles generated code before saving it.
#Import "Ks" { CompileScript }
Code := "MsgBox 'hello'"
Result := CompileScript(Code)
if Result.IsValid
FileAppend Code, A_ScriptDir "\generated.ks"
else
MsgBox "Generated code is invalid:`n" Result.Errors.Join("`n")
Checks the syntax of an existing file.
#Import "Ks" { ValidateScript }
Result := ValidateScript(A_ScriptDir "\other.ks")
MsgBox Result.IsValid ? "No syntax errors" : Result.Errors.Join("`n")
IsComponentAvailable, RunScript, Command-Line Options, How a Script Executes