lua-users home
lua-l archive

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

Roberto Ierusalimschy <roberto <at>> 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: .  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))
function tuple(...)
  local n = select('#', ...)
  return make_constructor(n)(...)

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

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

It's my opinion that the implementation of varargs in 5.1 is overly restrictive:

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