lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Remember there were multiple threads about adding semantic meaning to specific string objects, etc?

For example, say you want a date string, that acts like a string, but has added methods: (using io.write here to indicate its stringness)

local date = Date.new("1/1/1970")
io.write(date, "\n") --> 1970-01-01-T00:00:00.000+00:00
date = date:add("10y")
io.write(date, "\n") --> 1980-01-01-T00:00:00.000+00:00
io.write(date:as("ISO 8601"), "\n") --> 1980-01-01-T00:00:00.000+00:00
local t = {}
t[date] = true
io.write(next(t), "\n") --> 1980-01-01-T00:00:00.000+00:00

The way to do this is to do this:

local t = setmetatable({}, {__mode = "k"})
function Date.new(date, format)
  local processedDate = getDateString(date, format)
  t[processedDate] = {date_metadata_here}
  return processedDate
end
function string:as(format)
  if t[self] then
    return convertDate(self, format)
  else
    error("Not a date object")
  end
end

However, this causes conflicts and interning issues and stuff. So let's look at proposals to solve this:

There is a metamethod proposal that would make this better. Not perfect, but way better. It's __key. It would provide a general-purpose solution to this age-old problem:

local mt = {
  __index = {}
  __key = function(self) return self.date end
}
function Date.new(date, format)
  local processedDate = getDateString(date, format)
  return setmetatable({date=processedDate}, mt)
end
function mt.__index:as(format)
  return convertDate(self, format)
end

(I remember when we were always talking about the string metatable. There was always another proposal about strings and the string metatable and stuff.)

--
Disclaimer: these emails may be made public at any given time, with or without reason. If you don't agree with this, DO NOT REPLY.