to_s to __tostring
Lesson 37 of 48 in Coddy's Lua for Ruby Developers course.
Ruby objects can customize to_s for readable output. Lua tostring and print consult a __tostring metamethod stored in the object's metatable. Merely adding a similarly named ordinary instance field does not establish the same protocol. Return a string that reflects the current object's data. Formatting should not mutate the object or depend on another instance's fields.
Ruby
class Item
def to_s; "Item:pen"; end
end
puts Item.newLua 5.1
local Item={__tostring=function(self) return "Item:" .. self.name end}
print(setmetatable({name="pen"},Item))
Porting trap
Keep the metamethod on the actual metatable and the instance state on the instance table.
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
EasyImplement Model.new(name, count) and Model.__tostring to return name[count]. Input is name and nonnegative integer count on two lines. The app returns tostring(instance).
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: String conversion returns name[count], including zero counts, independently for multiple instances and repeated calls. 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("pen",3),Model.new("book",0)
assert(tostring(a)=="pen[3]" and tostring(b)=="book[0]","object text must reflect its own name and count")
assert(tostring(a)=="pen[3]","formatting must be repeatable")
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 Functions2Values 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 Inventory8Composition and Object Lookup
to_s to __tostringComposition Through TablesInheritance to Lookup ChainsDuck-Typed Message ContractsRuby == to Shared __eqRecap: Dispatch ReportsPractice on your own: Online Lua compiler