3

Many languages have methods for declaring constant values that can't be changed once created.

public static final int MAX_TIME = 25; // Java
const int MAX_TIME = 25;               // C++
const MAX_TIME = 25;                   // JavaScript

Is there an equivalent way to declare constants in AutoHotkey?

Stevoisiak
  • 23,794
  • 27
  • 122
  • 225

2 Answers2

3

One solution is to use a function.

MAX_TIME() {
    return 25
}
MsgBox % MAX_TIME()

Attempting to redefine the function produces Error: Duplicate function definition.

MAX_TIME() {
    return 25
}
MsgBox % MAX_TIME()
MAX_TIME() {
    return 22
}

Note that even after the function has been defined, creating a value with MAX_TIME = 20 is still allowed, so be consistent and always use the function instead of a variable.

Two other approaches are described at https://autohotkey.com/board/topic/90774-is-it-possible-to-create-constant/. The first is to simply use a variable and remember not to change it. This seems to be the preferred approach.

The second is to use a class property to store the constant, and override __Set() so that the value cannot be changed.

Python works pretty much the same way. See How do I create a constant in Python?

Jim K
  • 12,824
  • 2
  • 22
  • 51
  • 3
    Upvoted for "simply use a variable and remember not to change it" - naming it in ALL_CAPS is the usual mnemonic. Only public libraries would need more than this. – Dewi Morgan Sep 05 '17 at 18:40
  • @Dewi Morgan: Agreed, that is generally the best approach. My answer should have emphasized that. – Jim K Sep 05 '17 at 19:56
0

I simply create constants as variables with names starting with an underscore(_). Easy to remember not to change any such variable.