🎓 A1Learner
🔍
0 of 49 lessons completed

Lua Host Plug-ins

A host plug-in is a piece of guest code that registers itself in a host registry.

The host stores plug-ins in a registry

The register function appends to a table. The host then runs the stored function.

local registry = {}
local function register(fn)
  registry[#registry + 1] = fn
end
register(function()
  print("one")
end)
print(#registry)
registry[1]()

A plug-in registers through its environment

The plug-in chunk receives the register function. It calls register with its own function.

local registry = {}
local function register(fn)
  registry[#registry + 1] = fn
end
local plugin = load('register(function() print("plug one") end)', "plugin", "t", { register = register, print = print })
plugin()
print(#registry)

The host runs plug-ins in order

Two plug-ins register one after the other. The host walk prints first, then second.

local registry = {}
local function register(fn)
  registry[#registry + 1] = fn
end
local first = load('register(function() print("first") end)', "first", "t", { register = register, print = print })
local second = load('register(function() print("second") end)', "second", "t", { register = register, print = print })
first()
second()
for i = 1, #registry do
  registry[i]()
end

Example

local registry = {}
local function register(fn)
  registry[#registry + 1] = fn
end
local alpha = load('register(function() print("alpha") end)', "alpha", "t", { register = register, print = print })
local beta = load('register(function() print("beta") end)', "beta", "t", { register = register, print = print })
alpha()
beta()
print(#registry)
for i = 1, #registry do
  registry[i]()
end

Key points

  • Model: the host side here is modelled in Lua and no C code runs in this lesson.
  • Registry: a registry is a table that holds registered plug-ins.
  • Registration: a plug-in registers by calling a host function in its environment.
  • Order: the host runs registered plug-ins in registration order.
  • Separation: each plug-in only sees the names in its own environment.
  • Running: the host walks the registry and calls each stored function in turn.

In this example, the host defines a registry and a register function. Two plug-in chunks each call register with a printing function. The host prints the registry count and then walks the registry, so alpha prints before beta.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Two plug-ins register in order. Which runs first?