Menu
CoddyTech

Headers to require

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

C++17 separates declarations and definitions through headers and translation units. A namespace groups names but does not load a file at runtime. Lua uses executable chunks: a module usually creates a local table, attaches exported functions, and returns that table. Calling require("pricing") loads the module and normally caches its API value in package.loaded. Later calls retrieve that same value, so module state can be shared.

C++17

File-scope declarations, with standard headers supplied:

namespace pricing {
int& count() { static int value = 0; return value; }
}

Inside main, with standard headers supplied:

int& first = pricing::count();
int& again = pricing::count();
++first;
std::cout << again << '\n';

Lua 5.1

local first=require("math")
local again=require("math")
print(first == again)

Porting trap

Do not translate #include into repeated execution of a Lua file. Use a module name without its file extension, keep implementation helpers local, and return the public API. Avoid printing while loading a module because loading should not add unexpected program output.

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