Recap: Account Objects
Lesson 23 of 29 in Coddy's Lua for Luau 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 Luau Developers
1Syntax and Runtime
Run Lua ModulesInterpolation to TextFloor Division and NumbersBytes and UTF-8 LibrariesFalse Values and DefaultsConditional Expressions4Objects and Contracts
Types and Runtime ObjectsTyped self and Colon CallsIndependent Nested TablesStructural APIs to DelegationMetatable Library DifferencesEquality and Frozen ValuesRecap: Account ObjectsPractice on your own: Online Lua compiler