lua-users home
lua-l archive

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

Hi, all!

Lua 5.0.2

Say, I have three tables, A, B and C. I want user to transparently
read from them as from single table, first looking to A, then to B,
and then to C, and raising error if there is no requested key.

-- One can easily write joinN, but I need
-- optimized version for case with three tables.
join3 = function(A, B, C)
  local t = { }
    t, {
     __index = function(t, k)
         return A[k] or B[k] or C[k] or error("Not found" .. k)
     -- Skip __newindex for clarity.
  return t

There is one problem with my code: it will not detect entries with
value 'false'.

If I write the expression directly, it looks somewhat ugly:

local r = A[k] if r == nil then
  r = B[k] if r == nil then
    r = C[k] if r == nil then
      error("Not found")
return r

I can put all values to table like this:

first_valid = function(...) local i, r = next(arg); return r end
assert_valid = function(val, err) assert(val ~= nil, err); return val end
return assert_valid(first_valid(A[k], B[k], C[k]), "Not found")

But this envolves creation of varargs table, which I'd like to avoid
(and four extra function calls, which is probably ok :) ).

Do anyone know more elegant solution?