Menu
CoddyTech

Customize String Conversion

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

C requires an explicit display function to describe a struct. The example reads the fields through a pointer and formats them with printf. Lua can connect this behavior to string conversion by placing a function named __tostring in the instance metatable. Both tostring and ordinary printing use that hook. Return the assembled string from the hook instead of printing it there. A display operation should read object state without changing it, so repeated conversions describe the same value.

C

#include <stdio.h>
struct Item { const char *name; int count; };
static void item_print(const struct Item *item)
{
    printf("%s[%d]\n", item->name, item->count);
}
int main(void)
{
    struct Item item = {"pen", 3};
    item_print(&item);
    return 0;
}

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

An ordinary field named tostring does not install a conversion hook. Place __tostring directly on the metatable used by the instance, and return a string. A C format function is called explicitly; Lua discovers this particular hook by its exact name.

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 C Developers

Practice on your own: Online Lua compiler