Modules and require
Lesson 29 of 48 in Coddy's Lua for Go Developers course.
Go import selects compiled packages, whose exported identifiers begin with capitals. Lua require instead loads and executes a module chunk and caches its returned API table. Put exported functions on that table and keep helpers local. The Lua demonstration registers an in-memory loader; ordinary tasks use separate module files with silent initialization.
Go
package main
import ("fmt")
func subtotal(price,quantity int)int{return price*quantity}
func main(){
fmt.Println(subtotal(4,3))
}
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
Return the Lua API table and require it by module name without a .lua suffix.
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 Go Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte PositionsRecap: Format a Receipt4Functions and Closures
Functions and ArgumentsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
Absence and Table FieldsTruth and Default ValuesBranches and BoundsValues and Table IdentityRecap: Admission Rules3Iteration and Flow
Numeric for and Limitswhile and repeatArray Loops to ipairsFiltering and Early ExitRecap: Reading Stats6Ordering, Modules and Errors
Sorting and ComparatorsParsing with Lua PatternsModules and requireStatus Codes to pcallRecap: Validate a BatchPractice on your own: Online Lua compiler