Classes to Table Constructors
Lesson 33 of 48 in Coddy's Lua for Ruby Developers course.
Ruby new creates an instance and calls initialize. Lua has no built-in class keyword; a constructor is an ordinary function returning a fresh table, often connected to a shared method table with setmetatable. The __index field supplies missing-method lookup. Store per-instance values on the returned table. The constructor name new is a convention, not a special language operation. Modules return the constructor/method API for other files to require.
Ruby
class Item
attr_reader :n
def initialize(n); @n = n; end
end
a, b = Item.new(2), Item.new(5)
puts a.n + b.nLua 5.1
local Item={}
Item.__index=Item
function Item.new(n) return setmetatable({n=n},Item) end
local a,b=Item.new(2),Item.new(5)
print(a.n+b.n)
Porting trap
Returning the same prototype table for every construction shares all instance fields. Allocate a new table for each object.
Implement the required public API in the editable Lua modules. The visible locked main.lua loads them with require, supplies input/output, and checks specified module behavior. Keep the module names and return contracts.
Challenge
EasyIn model.lua, implement Model.new(n) to create an instance holding n. The app creates two instances from two integer lines and returns their sum.
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: Model.new(n) must retain n on a fresh independent instance. 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(2),Model.new(-3)
assert(a.n==2 and b.n==-3,"Model.new must retain each supplied n")
a.n=9
assert(b.n==-3,"instances must own independent n state")
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 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