Constants in Lua

Go supports constants of character, string, boolean, and numeric values.

local constants = {}

-- Declare constant value
constants.s = "constant"

print(constants.s)

-- 'const' statement can appear anywhere a 'var' statement can
constants.n = 500000000

-- Constant expressions perform arithmetic with arbitrary precision
constants.d = 3e20 / constants.n
print(constants.d)

-- A numeric constant has no type until it’s given one, such as by an explicit conversion
print(math.floor(constants.d))

-- Example where math.sin function expects a number type (float in this case)
print(math.sin(constants.n))

To run the program, you can save the code in a .lua file and execute it using a Lua interpreter.

$ lua constants.lua
constant
6e+11
600000000000
-0.28470407323754

This example shows how to define and use constants in Lua. Lua doesn’t have built-in support for const keyword like some other languages, but you can use tables to simulate constants. You can perform arithmetic with constant expressions and assign types as needed.

Next example: For.