lua-users home
lua-l archive

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


On Mon, Apr 2, 2012 at 11:47 AM, Rob Kendrick <rjek@rjek.com> wrote:
> 
> 
> foo = t[1, 2, 3] -> __slice(t, 1, 2, 3)
> t[1, 2, 3] = foo -> __newslice(t, foo, 1, 2, 3)
> 
> Notes:
>      * Avoids reuse of __index and __newindex, due to stickyness
>        making it compatible with existing code.
>      * Syntax is backwards compatible with existing table
>        deferencing.
>      * __index and __newindex implementations can simply call the
>        slice equivalent if they want to share functionality.
>      * Slicing either in or out should raise a runtime error if there
>        isn't a suitable metamethod.
>      * From a different angle, a table deference is just a function
>        call waiting to be discovered.
> 
Maybe my solution is to simple for your needs, but I think this is already possible using tables as indices.

I just hacked this little code as demonstation:
mt = { 
__index = function(t,k)
  local r = {}
  for i=k[1],k[2] do
    r[i] = t[i]
  end
  return r
end,
__newindex = function(t,k,v)
  for i=k[1],k[2] do
    rawset(t, i, v)
  end
end

}
t = {"a", "b", "c", "d"}

setmetatable(t, mt)
t[{5,20}] = 1
print(table.concat(t[{1,10}],":"))

The output is: a:b:c:d:1:1:1:1:1:1


  Maybe I am too naive, but I think this is already possible using tables as indexes. 
 I just hacked this little code as example: 
 mt = {  
 __index = function(t,k) 
 local r = {} 
 for i=k[1],k[2] do 
 r[i] = t[i] 
 end 
 return r 
 end, 
 __newindex = function(t,k,v) 
 for i=k[1],k[2] do 
 rawset(t, i, v) 
 end 
 end 
 } 
 t = {"a", "b", "c", "d"} 
 setmetatable(t, mt) 
 t[{5,20}] = 1 
 print(table.concat(t[{1,10}],":")) 
 The output is: a:b:c:d:1:1:1:1:1:1 

 
Now of course the t[{_,_}] syntax is not as nice as t[_,_] but it does the trick. Unfortunately it is not possible to make a solution by syntactic sugar as the syntax t{_,_} already translates to t({_,_}). 



 Now this has the overhead of creating a table each time you make an access this way, but it's as flexible as it can get. 



 You could also simulate the right hand side by defining the __call metamethod for your table, than you could write foo = t(1, 2, 3) --> __call(t, 1, 2, 3), this doesn't work on the LHS though. 


--
Thomas