How to create readonly constant variables


Lua does not support static constants. However, there are a few options that could help you to avoid overwriting static constants.

  • Use ALLCAPS to let other programmers know that these variables are constants
  • Use use a readonlyConstant() function to avoid overwriting constants

Task [top]

Use the readonlyConst() function to prevent programmers from updating static constant variables.

Implementation [top]

It is a recommended Best Practice Name “constant” values using ALLCAPS to indicate that they are CONST type values and should not be changed. However please be aware that this just a convention as there is no static CONST type in Lua (unlike compiled languages like C, C++ etc.). Using ALLCAPS lets programmers know that these variables are constants and should not be changed (if they are named like other variables there is no easy way to tell).

In addition you can use a readonlyConstant() function to raise a warning/error when a programmer tries to update a constant value:

  1. Add the Interfaceware Support repository in Iguana.
  2. Import the Immutable Constant Example channel from the Interfaceware Support repository.
  3. Review the main.lua and see how ConstantConfigs module is used in the Main function.



How it works [top]

In Main.Lua above:

  • Line 2: Imports constants module
  • Line 6: Uses LEFT constants
  • Line 9: Try to overwrite LEFT constants but throw an error in ConstantConfigs.lua

In ConstantConfigs.lua:

  • Line 1 – 9: Readonly function that prevent programmer from updating the constants
  • Line 12 – 16: Defines constants variables

More information [top]

Leave A Comment?

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.