Recap: Account Objects
Lesson 36 of 48 in Coddy's Lua for C++ Developers course.
Challenge
MediumImplement Model.new(balance) and Model:withdraw(amount) in model.lua. Withdraw returns true and subtracts only when amount is nonnegative and affordable. Input is initial balance followed by withdrawal amounts. Return finalBalance:acceptedCount. Failed operations leave balance unchanged.
Edit app.lua, model.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: withdraw returns a boolean; negative or unaffordable amounts leave balance unchanged, zero and exact-balance withdrawals succeed, and accounts are independent. The locked driver checks this behavior before calling app.run. These checks print nothing when successful.
Try it yourself
-- Public API checks
do
local Model=require("model")
local a,b=Model.new(5),Model.new(8)
assert(a:withdraw(6)==false and a.balance==5,"overdraft must leave balance unchanged")
assert(a:withdraw(-1)==false and a.balance==5,"negative withdrawal must not mutate")
assert(a:withdraw(0)==true and a.balance==5,"zero withdrawal is valid")
assert(a:withdraw(5)==true and a.balance==0,"exact withdrawal succeeds")
assert(b.balance==8,"accounts must be independent")
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 Functions7Objects and Owned State
Validation Before MutationTables as Instancesself and Colon CallsIndependent Instance TablesRecap: Account Objects2Values and Decisions
Absence and Missing FieldsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission RulesPractice on your own: Online Lua compiler