🎓 A1Learner
🔍
0 of 49 lessons completed

Lua Project: Plug-in System

A plug-in system is a host program that lets small add-on pieces register and run in order. The host stays in charge while the add-ons supply the features.

The registry keeps registration order

Each registration appends one name. The list then reads in the order plug-ins joined.

local host = { plugins = {} }
local function register(name) host.plugins[#host.plugins + 1] = name end
register("alpha")
register("beta")
print(table.concat(host.plugins, ", "))

A plug-in receives a small API

The host passes one API table to the plug-in. The plug-in uses only the function it was given.

local api = { say = function(msg) print("said: " .. msg) end }
local function plugin(api) api.say("hello") end
plugin(api)

A failing plug-in does not stop the rest

Each plug-in runs inside pcall. The second plug-in still runs after the first one fails.

local plugins = {
  function() error("boom", 0) end,
  function() print("second ran") end
}
local okCount = 0
local failCount = 0
for _, run in ipairs(plugins) do
  local ok = pcall(run)
  if ok then okCount = okCount + 1 else failCount = failCount + 1 end
end
print(okCount .. " ok, " .. failCount .. " failed")

Example

local host = { plugins = {} }
local function register(name, run) host.plugins[#host.plugins + 1] = { name = name, run = run } end
local api = { say = function(msg) print(msg) end }
register("welcome", function(api) api.say("welcome") end)
register("broken", function(api) error("boom", 0) end)
register("bonus", function(api) api.say("bonus") end)
local ran = 0
local failed = 0
for _, plugin in ipairs(host.plugins) do
  local ok = pcall(plugin.run, api)
  if ok then ran = ran + 1 else failed = failed + 1 end
end
print(ran .. " ran, " .. failed .. " failed")

Key points

  • Host: the host owns a registry table and the running order.
  • Registry: each plug-in adds its own run function to the registry.
  • Limited API: each plug-in receives only the small API table the host passes it.
  • Order: the host runs registered plug-ins in registration order.
  • Guard: a failing plug-in is caught by pcall, so later plug-ins still run.
  • Report: the host prints which plug-ins ran and which failed.

In this example, three plug-ins register in order, and each receives the same small API table. The welcome plug-in prints first. The broken plug-in fails inside pcall, so the bonus plug-in still runs. The final line reports two runs and one failure.

Note

the host side here is modelled in Lua, with no C code involved.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A plug-in in the middle of the list fails. What happens to the plug-ins after it?