Ledger: Withdraw Stock
Lesson 44 of 48 in Coddy's Lua for C++ Developers course.
Challenge
MediumContinue the preceding files. Keep ADD behavior. Add TAKE name quantity for nonnegative integer quantities. A take succeeds only for an existing name with enough units; failed takes leave stock unchanged. A zero take succeeds only for an existing name. Retain zero-balance names. Change report.lua to return totalUnits:accepted:rejected instead of the previous report. Count each successful command once. Inputs in this step are well-formed ADD or TAKE commands.
Edit app.lua, inventory.lua, parser.lua, report.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: Inventory.new() creates independent stock state. apply(command) must accept valid ADD commands, return true and aggregate quantity in stock[name]. This shared API check is the same in all four project drivers. The locked driver checks this behavior before calling app.run. These checks print nothing when successful.
Try it yourself
-- Public API checks
do
local Inventory=require("inventory")
local a,b=Inventory.new(),Inventory.new()
assert(a:apply({kind="ADD",name="probe",quantity=2})==true,"inventory accepts valid additions")
assert(a:apply({kind="ADD",name="probe",quantity=3})==true and a.stock.probe==5,"inventory aggregates repeated additions")
assert(next(b.stock)==nil,"inventories must own independent stock")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
All lessons in Lua for C++ 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
Absence and Missing FieldsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission Rules3Iteration and Flow
Counted Loops to Numeric forwhile and repeatIndexes and ipairsFiltering and Early ExitRecap: Reading Stats6Ordering, Modules and Errors
Sorting and ComparatorsPatterns Instead of RegexHeaders to requireExceptions to pcallRecap: Validate a Batch9Project: Stock Ledger
Ledger: Add StockLedger: Withdraw StockPractice on your own: Online Lua compiler