lua-users home
lua-l archive

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

On 05/09/2012 08:52 AM, Luiz Henrique de Figueiredo wrote:
Given a function that returns multiple values, is there a way to construct a table, but where each value is assigned a name rather than an index

You'll need a helper function:
	function namedtable(name,...)
	local t=namedtable({"day", "month", "year"},f())
	for k,v in pairs(t) do print(k,v) end

Since you'd probably repeat that with the same names, returning a function would work well. This function preserves the numeric keys, like many database libraries do.

function columns(...)
  local name = table.pack(...)
  return function(...)
    local t = table.pack(...)
    if t.n == 0 then return nil end
    local n = math.min(name.n, t.n)
    t.n = nil
    for i = 1,n do
      t[name[i] or 0] = t[i]
    return t

function parsedates(str)
  local date = columns("day", "month", "year")
  local match = string.gmatch(str, "(%d%d)/(%d%d)/(%d%d%d%d)")
  return function()
    return date(match())

for date in parsedates("28/07/1993 16/12/2011") do
  print("%a %b %e, %Y",os.time(date)))

- tom