🎓 A1Learner
🔍
0 of 49 lessons completed

Lua Host Reloading

Hot reloading is loading a changed module again without restarting the host.

Require loads the module once

The module file returns a label. The host prints that label.

local mod = require "greetmod"
print(mod.label)

A second require returns the cached module

The host rewrites the module file. A plain second require still returns the old label.

local first = require "greetmod"
local file = io.open("greetmod.lua", "w")
file:write('return { label = "two" }\n')
file:close()
local second = require "greetmod"
print(first.label, second.label)

Clearing the cache loads the changed file

The host rewrites the file and clears the cache entry. The fresh require returns the new label.

local first = require "greetmod"
local file = io.open("greetmod.lua", "w")
file:write('return { label = "two" }\n')
file:close()
package.loaded["greetmod"] = nil
local second = require "greetmod"
print(first.label, second.label)

Example

local first = require "greetmod"
print(first.label)
print(first.shout())
local file = io.open("greetmod.lua", "w")
file:write('return { label = "two", shout = function() return "TWO" end }\n')
file:close()
package.loaded["greetmod"] = nil
local second = require "greetmod"
print(second.label)
print(second.shout())

Key points

  • Model: the host side here is modelled in Lua and no C code runs in this lesson.
  • Module cache: the module cache is a table that holds modules already loaded.
  • Require: require returns the cached module instead of loading the file again.
  • Clearing: clearing the cache entry drops the old module from the cache.
  • Reload: a fresh require after clearing loads the changed file.
  • Old reference: a variable holding the old module keeps the old values.

In this example, the host requires the module and prints its label and shout. It then rewrites the module file and clears the cache entry. The fresh require loads the new module, so the new label and shout print next.

Note

the new module file must be in place before the fresh require runs.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

After editing a module file, what makes require load the new version?