Metatable Library Differences
Lesson 21 of 29 in Coddy's Lua for Luau Developers course.
Metatables are familiar, but the supported hooks depend on the runtime version. Luau allows a table __len metamethod; Lua 5.1 does not use that hook for tables. An apparent length property can therefore silently change when ported. Use an explicit method for such a domain count, or keep a genuinely dense sequence when array length is intended. The shared __tostring hook can format objects in both languages, and the task uses that portable hook. Keep the formatter dependent on each instance rather than closing over one constructor argument. Type annotations do not register hooks; actual metatable fields do.
Luau
local t = setmetatable({10,20}, {__len=function() return 9 end})
print(#t)Lua 5.1
local t = setmetatable({10,20}, {__len=function() return 9 end})
print(#t)Porting trap
The examples intentionally produce different lengths: the source invokes a hook, while Lua 5.1 measures the dense table itself.
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 Luau Developers
1Syntax and Runtime
Run Lua ModulesInterpolation to TextFloor Division and NumbersBytes and UTF-8 LibrariesFalse Values and DefaultsConditional Expressions4Objects and Contracts
Types and Runtime ObjectsTyped self and Colon CallsIndependent Nested TablesStructural APIs to DelegationMetatable Library DifferencesEquality and Frozen ValuesRecap: Account ObjectsPractice on your own: Online Lua compiler