0Pricing
Lua Academy · Lesson

__tostring and __len

Control string representation and the # operator via metamethods.

__tostring Metamethod

__tostring is called when tostring(obj) is invoked, and also by print() (which calls tostring on each argument). Define it to provide a human-readable representation of your custom objects.

local Point = {}
Point.__index = Point
Point.__tostring = function(p)
  return string.format("Point(%.2f, %.2f)", p.x, p.y)
end

function Point.new(x,y)
  return setmetatable({x=x,y=y}, Point)
end

local p = Point.new(3.14, 2.72)
print(p)            -- Point(3.14, 2.72)
print(tostring(p))  -- Point(3.14, 2.72)

__len for Sequences

__len is called when the # operator is applied to a table with this metamethod. In Lua 5.2+, __len is always called for tables; in 5.1 it's only called for userdata. Use it to define "length" for custom containers.

local Queue = {}
Queue.__index = Queue
Queue.__len = function(q) return q._tail - q._head + 1 end

function Queue.new()
  return setmetatable({_data={},_head=1,_tail=0}, Queue)
end
function Queue:push(v)
  self._tail = self._tail + 1
  self._data[self._tail] = v
end
function Queue:pop()
  if self._head > self._tail then return nil end
  local v = self._data[self._head]
  self._head = self._head + 1
  return v
end

local q = Queue.new()
q:push("a"); q:push("b"); q:push("c")
print(#q)   -- 3

All lessons in this course

  1. Introduction to Metatables
  2. __index and __newindex
  3. Arithmetic Metamethods
  4. __tostring and __len
← Back to Lua Academy