Readable Objects
Lesson 37 of 48 in Coddy's Luau for Go Developers course.
Go fmt can use a String() string method for a Stringer representation. Luau uses __tostring installed in an attached metatable. An ordinary tostring field does not activate that hook. Keep formatting stable and separate from object mutation.
Go comparison
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"})
}
Luau behavior
__tostring belongs on the metatable used by the instance. It produces readable text without changing the object. A normal field called tostring is not automatically consulted. Keep text stable for testing instead of exposing default table addresses.
local Item={__tostring=function(self) return "Item:" .. self.name end}
print(setmetatable({name="pen"},Item))Expected Luau output:
Item:penChallenge
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.luau, model.luau. The visible locked main.luau 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 Luau for Go Developers
1First Luau Programs
Run Luau ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte IndexesRecap: Format a Receipt4Functions and Closures
Functions and ReturnsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
Missing Fields and OptionalsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission Rules5Tables as Collections
Lists as Dense TablesDictionaries and pairsSets and MembershipAliasing and Shallow CopiesRecap: Count Inventory8Composition and Object Lookup
Readable ObjectsComposition and DelegationPrototype Lookup ChainsPolymorphism by ProtocolValue Equality MetamethodsRecap: Dispatch ReportsPractice on your own: Online Luau compiler