Readable Objects
Lesson 37 of 48 in Coddy's Lua for GDScript Developers course.
GDScript objects can implement _to_string to control the text produced by str. Lua offers related behavior through a __tostring metamethod on an object's metatable. Calling tostring then invokes that function with the object as its argument. Return one string with the intended format; do not print inside the formatter. Defining a same-named field on the instance is insufficient when the runtime looks in its metatable. The examples format a stack as a label followed by a bracketed count. This gives callers predictable display text without exposing an engine instance identifier or a Lua table address.
GDScript 4
extends SceneTree
class Stack:
var label
var count
func _init(item_label, item_count):
label = item_label
count = item_count
func _to_string() -> String:
return label + "[" + str(count) + "]"
func _init():
print(str(Stack.new("potion", 3)))
quit()Lua 5.1
local Stack = {}
Stack.__index = Stack
function Stack.new(label, count)
return setmetatable({label = label, count = count}, Stack)
end
function Stack.__tostring(self)
return self.label .. "[" .. self.count .. "]"
end
print(tostring(Stack.new("potion", 3)))Porting trap
The GDScript hook is _to_string; Lua looks for __tostring on the metatable. Renaming the hook is not enough unless the metatable is attached.
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 GDScript Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte IndexesRecap: Format a Receipt4Functions and Closures
Functions and ReturnsDefaults and Missing ValuesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
null and Missing FieldsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission Rules5Tables as Collections
Arrays 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 Lua compiler