Re: Defining a function argument during index lookup
[
Date Prev][
Date Next][
Thread Prev][
Thread Next]
[
Date Index]
[
Thread Index]
- Subject: Re: Defining a function argument during index lookup
 
- From: Peter Shook <peter.shook@...>
 
- Date: 2002年1月06日 10:30:12 -0500
 
Peter Loveday wrote:
> 
> Is there a way I can insert an argument for a function during
> the index lookup handler of a table, where this lookup is returning
> a function?
> 
> I am trying to re-direct a function call from the global index
> handler to a userdata handler, based on a currently 'active'
> object. The intention being that I can create a kind of 'using'
> directive :
> 
> obj:FuncA(...)
> obj:FuncB(...)
> obj:FuncC(...)
> 
> with:
> 
> UsingObj(obj)
> FuncA(...)
> FuncB(...)
> FuncC(...)
> 
> I have successfully set up the handler tables such that the global
> handler queries the active 'obj', and it will return FuncA (or whatever)
> as required. However, I cannot find a way to simulate the ':', which
> magically inserts obj as the first argument... I have tried pushing
> multiple values on to the stack from my handler, but it doesn't seem
> to help.
The lastest version of Lua is great for stuff like this.
function class( t )
 t = t or {}
 t.index = t
 t.new = new
 return t
end
function new( class, init )
 init = init or {}
 return eventtable( init, class )
end
local eventtable, type
 = eventtable, type
 
local ind
function ind(t,i)
 return type( t[i] ) == 'function' and
 eventtable( {}, { settable=t, gettable=t, call=t[i] } ) or t[i]
end
function using( obj )
 eventtable( globals(), { index = function(t,i) return ind(obj,i) end }
)
end
A = class{
 data = 2
}
function A:pd(x)
 print( "x", x, "data", self.data )
end
function A:ps(x)
 print( "x", x, "stuff", self.stuff )
end
a = A:new{ stuff = 3 }
b = A:new{ stuff = 4 }
With the above you can do:
$ lua using.lua -i
> using(a)
> = data,stuff
2 3
> = pd(11),ps(22)
x 11 data 2
x 22 stuff 3
nil
> using(b)
> = data,stuff
2 4
> = pd(33),ps(44)
x 33 data 2
x 44 stuff 4
nil
> 
Lua has always been a better extension language than Perl. Now it's
just as good a scripting language.
- Peter