Recap: Account Objects
Lesson 36 of 48 in Coddy's Lua for Ruby 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 Ruby Developers
1From Ruby to Lua
Run Lua Modulesputs to printRuby Locals and Lua ScopeRuby Integer to Lua NumberStrings as Byte SequencesRecap: Format a Receipt4Methods, Functions, Closures
Methods to FunctionsKeyword Defaults to OptionsTuples to Multiple ResultsBlocks and Captured LocalsRecap: Pricing Functions7Objects and Owned State
Validate Before MutatingClasses to Table ConstructorsBound Methods and Colon CallsIndependent Nested StateRecap: Account Objects2Values and Decisions
nil Values and Missing FieldsShared Truth Ruleselsif to elseifRuby == and Table IdentityRecap: Admission Rules5Arrays and Hashes to Tables
Arrays to Dense TablesHash Records and pairsSet Membership with Keysdup and Table CopiesRecap: Count InventoryPractice on your own: Online Lua compiler