Const variables

I want to define a constant value that can’t be changed dynamically to reduce potential bugs. This is standard features in most programming languages.

const var = 1

var = 2 --> Error: var is const
25 Likes

This was already discussed on the Luau repo before being turned down. In one of the comments it’s labeled as only having a very small value for correctness.

6 Likes

How many times are you planning on referencing these variables?

If it’s only a few places in your scripts then how about just putting that value in your lines of code instead of a variable.

This is horrid practice. In months you’ll forget what those values are supposed to represent, and that makes it error prone and harder to change the value if you ever need to.


Could you store all of your constants in a module that returns them in a frozen table? Then you have your immutability.

9 Likes

What PeZsmistic said is the big-brained move.

uh this isn't what he meant

ModuleScript:

Consts = {
	pi = 3.14
}
return function(toGet)
	return Consts[toGet]
end

Script:

GetConst = require(Path.To.ModuleScript)

print(GetConst('pi'))

I didn’t even know this was a thing, but apparently you can just do this:

Constants = {
	pi = 3.14
}

table.freeze(Constants)

This is what I was originally thinking:

Pretty sure using metatables disables Luau optimizations, but if you don’t care about that, you could do it this way with metatables:

function CONST(constsTable,shouldError)
	if shouldError == nil then
		shouldError = true
	end
	local proxyTable = {}
	local metaTable = {
		__newindex = function(tab,indx,val)
			if shouldError then
				error("Tried to modify index "..indx.." of a constant table!")
			end
			return
		end,
		__index = function(tab,indx,val)
			return constsTable[indx]
		end
	}
	return setmetatable(proxyTable, metaTable)
end

so like

Constants = CONST({
	Pi = 3.14
})

Constants.Pi = 3 -- ERRORS

or

Constants = CONST({
	Pi = 3.14
},false)

Constants.Pi = 3

print(Constants.Pi) -- 3.14

(ik i could probably make metaTable and constsTable the same table to save some resources)

3 Likes

All you need to do is call table.freeze before returning from the module.

oh wow, I didn’t know table.freeze was a thing!
that’s neat

I wish it was documented on the api docs >:(

Edit: Looks like no one has reported this, so I took the liberty of doing so.

3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.