Menu
CoddyTech

Readable Objects

Lesson 37 of 48 in Coddy's Lua for Python Developers course.

Python __str__ customizes string conversion. Lua looks for __tostring in an object metatable. Return a string from that function. Keep display behavior separate from state mutation.

Python

class Item:
    def __str__(self): return "Item:pen"
print(Item())

Lua

local Item={__tostring=function(self) return "Item:" .. self.name end}
print(setmetatable({name="pen"},Item))

Porting trap

A method named tostring on the instance is not the special hook. The metamethod must be stored under the exact name in the metatable.

challenge icon

Challenge

Easy

Implement 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))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lua for Python Developers

Practice on your own: Online Lua compiler