lua-users home
lua-l archive

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


Lavergne Thomas wrote:
> On Tue, Jul 10, 2007 at 01:54:28PM -0500, Rici Lake wrote:
>> On 10-Jul-07, at 1:37 PM, Lavergne Thomas wrote:
>>> at start I have :
>>>  value = object[idx]
>>> it was simple and elegant. I've hopped for this :
>>>  value, delta = object[idx]
>>> but it's impossible.
>> 
>> Sure, but you could certainly implement it as:
>> 
>>   value, delta = object(idx)
>> 
>> Just give object a __call metamethod.
> 
> Sorry to be so annoying and rejecting your suggestions, but the
> __call metamethod is already used in theses objects. (and this also
> break compatibility with existing code)  
> 
> [...]
> 
> I will stuck with a new method in my object, an __index shortcut and
> try to forgot this dream... 

Another solution that no one else proposed is to pass several keys to
your __index metamethods. You can do that by creating a table (this
could work with a closure too) on the fly. I use that technique to index
pixels in an image userdata that I wrote, which I think is pretty
elegant (but very slow):

function newtexture(height, width, generator)
   local img = libimg.new(height, width, 3, 8) -- 3 components, 8 bits
   for y=1,height do for x=1,width do
	local color = generator(x, y)
      img[{y,x,1}] = color.r
      img[{y,x,2}] = color.g
      img[{y,x,3}] = color.b
   end end
   return img
end

In your case that could look like that:

-- old code keeps working without table
value = object[idx]
-- new code can use the table key
value, delta = object[{idx,'v'}], object[{idx,'d'}]
-- you can alternatively use a closure that __index will call
local ID = function(a,b) return function() return a,b end end
value, delta = object[ID(idx,'v')], object[ID(idx,'d')]