lua-users home
lua-l archive

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


Roberto Ierusalimschy <roberto <at> inf.puc-rio.br> writes:
> Another option is to implement tuples. We can implement them as C
> functions with upvalues (PiL2, p. 257).

This was a rather clean approach in pure Lua:
http://lua-users.org/wiki/FunctionalTuples .  It has been appended with an
example that handles arbitrary tuple size via code generation.  The code
generation is the awkward part and often resembles something like this:

local function make_constructor(n)
  local ts = {}; for i=1,n do ts[i] = "a" .. i end
  local names = table.concat(ts, ",")
  local s = "local " .. names ..
     " = ...; return function(f) f(" .. names .. ") end"
  return assert(loadstring(s))
end
function tuple(...)
  local n = select('#', ...)
  return make_constructor(n)(...)
end

The above could be avoided if we could write this (why can't we?):

function tuple(...)
  return function(f) return f(...) end
end

It's my opinion that the implementation of varargs in 5.1 is overly restrictive:
http://lua-users.org/wiki/VarargTheSecondClassCitizen

Also noteworthy: not only can tuples be implemented in terms of
functions, but so can Lua tables ( http://lua-users.org/wiki/MutableFunctions )
and probably near any other data structure.  That's not to say they necessarily
should be though.