[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Implementing properties
- From: Mark Hamburg <mhamburg@...>
- Date: Wed, 05 Apr 2006 07:38:53 -0800
Late reply...
Yes, you can do this but you take a speed hit on method lookup because you
can't just use an __index table and let the Lua VM do the work but instead
need to have a function do the lookup to know whether it is dealing with a
method that can just be returned or a property that must be evaluated.
Here is an example of such an __index function.
local methods = {
length = calc_length
}
local getters = {
x = get_x,
y = get_y
}
function __index( t, k )
local method = methods[ k ]
if method then
return method
end
return getters[ k ]( t, k )
-- add error reporting as desired
end
For the case of setting properties, a __newindex function can do the
additional dispatch:
local setters = {
x = set_x,
y = set_y
}
function __newindex( t, k, v )
setters[ k ]( t, k, v )
-- add error reporting as desired...
end
What would speed method lookup in the first case would be having __index
metamethods also receive the object at the head of the index chain rather
than just the object at the end of the chain. Then one could store the
methods as an __index table with a metatable containing an __index function
that dealt with properties. This would, however, slow property lookup.
Mark
on 3/6/06 9:38 AM, Jose Marin at jose_marin2@yahoo.com.br wrote:
> Sorry, I wasn't clear on my question!
>
> There are som binders (tolua, for example), that
> allows to create and access objects methods and
> properties.
>
> I would like to creat my own binder.
>
> I know how to bind methods, but properties are a
> little trickier to me.
>
>
> If I have this class
>
> class Vector2D{
> public:
> int x;
> int y;
> public:
> Vector2D();
>
> int lenght();
> };
>
>
> I would like to map the method 'lenght' to the C
> funcion Vector2D_lenght, the property 'x' to
> Vector2D_get_x and Vector2D_set_x and the property 'y'
> to Vector2D_get_y and
> Vector2D_set_y.
>
>
> vec = Vector2D()
>
> vec.x = 10 -- calls Vector2D_set_x
> vec.y = 5 -- calls Vector2D_set_y
>
> local x = vec.x -- calls Vector2D_get_x
> local y = vec.y -- calls Vector2D_get_y
>
> vec:lenght() -- calls Vector2D_lenght
>
>
>
> Is there some way to provide fast access to these
> function?
>
>
>
>
>
>
>
>
>
>
>
> _______________________________________________________
> Yahoo! doce lar. Faça do Yahoo! sua homepage.
> http://br.yahoo.com/homepageset.html
>