Menu
CoddyTech

Modules and require

Lesson 29 of 48 in Coddy's Lua for C Developers course.

C typically separates declarations in headers from definitions in compiled translation units. Including a header does not execute a runtime loader. Lua require loads a module on demand and caches its returned API value in package.loaded. A usual module file creates a local table, adds public functions, and returns that table. Local helpers remain private. The standalone examples package a subtotal function in an API: C uses a structure containing a function pointer, while Lua registers an in-memory loader with package.preload. A normal project would put that loader's body in pricing.lua.

C

#include <stdio.h>
struct Pricing { int (*subtotal)(int, int); };
static int subtotal(int price, int quantity) {
    return price * quantity;
}
static const struct Pricing *pricing_api(void) {
    static const struct Pricing api = {subtotal};
    return &api;
}
int main(void) {
    const struct Pricing *pricing = pricing_api();
    printf("%d\n", pricing->subtotal(4, 3));
    return 0;
}

Lua

package.preload["pricing_demo"] = function()
  local M = {}
  function M.subtotal(price, quantity)
    return price * quantity
  end
  return M
end
local pricing = require("pricing_demo")
print(pricing.subtotal(4, 3))

Porting trap

Call require("pricing") with a module name, not a filename ending in .lua. Requiring the same module normally returns its cached API, so mutable module state is shared between callers.

challenge icon

Challenge

Easy

Input is integer price and nonnegative quantity. Implement subtotal in pricing.lua and call it from app.lua. Return the product. Do not print during require.

Edit app.lua, pricing.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.

Public API checks: pricing.subtotal(price, quantity) must work independently of app.run, including zero quantity and signed price. The locked driver checks this behavior before calling app.run. These checks print nothing when successful.

Try it yourself

-- Public API checks
do
local pricing=require("pricing")
assert(pricing.subtotal(4,3)==12 and pricing.subtotal(4,0)==0 and pricing.subtotal(-2,3)==-6,"pricing.subtotal must implement the public product API")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lua for C Developers

Practice on your own: Online Lua compiler