Imports to require
Lesson 29 of 48 in Coddy's Lua for Python Developers course.
A Lua module is a chunk that returns an API value, usually a table. require("pricing") searches for pricing.lua on the module path and caches the returned value in package.loaded. Modules should not print during import.
Python
import math
import math as again
print(math is again)Lua
local first=require("math")
local again=require("math")
print(first == again)Porting trap
Use dot-separated module names, not file extensions, in require. Local declarations stay private unless exported on the returned table. This course keeps all modules beside the locked main file.
Challenge
EasyInput 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))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lua for Python Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte IndexesRecap: Format a Receipt4Functions and Closures
Functions and ReturnsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
None and Missing FieldsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission Rules3Iteration and Flow
Ranges to Numeric forwhile and repeatenumerate to ipairsFiltering and Early ExitRecap: Reading Stats6Ordering, Modules and Errors
Sorting and ComparatorsPatterns Instead of RegexImports to requireExceptions to pcallRecap: Validate a BatchPractice on your own: Online Lua compiler