What is hard-coding?

A programmer can choose to put either constant (immediate addressing) or variable (relative addressing) values into a program. Constants cannot be changed by code later in the program. This is known as "hard-coding". The alternative is to use variables/attributes that can change. As a programmer you need to decide whether to hard-code aspects of your solution or not. It is often quicker to hard-code, but it has a lot less flexibility for adding features to your game later. Good programmers will use the computational thinking approach of, "thinking ahead" to decide which is most appropriate for the problem being solved.

For example, if you know your game will only ever be played on an 8x8 grid then it makes sense to hard-code these values and use constants. Remember it is especially important in games development to have the most optimised code to ensure high frame rates. Hard-coding will enable the compiler to create the most efficient and optimised code. However, if later you want different levels in the game to use different grid sizes, then it makes more sense to use a variable and assign it the number 8 instead.

An example from the Incoming tutorial:

function init(self)
	-- set the random number seed and discard the first value
	math.randomseed(os.time())
	math.random()
	self.spawn_rate = 90
end

function update(self, dt)
	local spawn = math.random(1,self.spawn_rate)
	if spawn == 1 then
What does this code do?

Here we used an attribute called spawn_rate and set it to the value 90. This means we can easily change this value later if we want to make the game easier or harder.

An alternative approach would be to hard-code the value 90 instead. However, this would mean we couldn't change it later.

function init(self)
	-- set the random number seed and discard the first value
	math.randomseed(os.time())
	math.random()
end

function update(self, dt)
	local spawn = math.random(1,90)
	if spawn == 1 then
What does this code do?

Note, the value 90 has been "hard coded" into the program. Only the programmer can change this at design-time. It cannot be changed at run-time.

This results in more efficient machine code because it does not require the attribute to be fetched from memory, but can only be used when the value can never change.