Customize String Conversion
Lesson 37 of 48 in Coddy's Lua for Go Developers course.
Go fmt recognizes the Stringer interface’s String method for readable formatting. Lua uses __tostring on an object’s metatable instead. An ordinary tostring field does not automatically become a conversion hook. Return the required string without changing state and keep readable representation separate from object equality.
Go
package main
import ("fmt")
type Item struct {Name string}
func(i Item) String()string{return "Item:"+i.Name}
func main(){
fmt.Println(Item{Name:"pen"})
}
Lua
local Item = {}
function Item.__tostring(self)
return self.name .. "[" .. self.count .. "]"
end
local item = setmetatable({name = "pen", count = 3}, Item)
print(item)Porting trap
Install __tostring on the metatable and return a string.
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 Go Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte PositionsRecap: Format a Receipt4Functions and Closures
Functions and ArgumentsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
Absence and Table FieldsTruth and Default ValuesBranches and BoundsValues and Table IdentityRecap: Admission Rules5Tables as Collections
Arrays to Dense TablesRecords and Dynamic KeysSets and MembershipAliasing and Shallow CopiesRecap: Count Inventory8Composition and Object Lookup
Customize String ConversionDelegate to a CollaboratorBuild Prototype Lookup ChainsUse a Shared Method ProtocolCompare Values with __eqRecap: Dispatch ReportsPractice on your own: Online Lua compiler