[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Using closures was:Re: Lua5.0 new "For" question
- From: Eero Pajarre <epajarre@...>
- Date: Sat, 28 Dec 2002 00:31:47 +0200
Peter Hill wrote:
I'm having trouble trying to imagine a way to get the same functionality
(which doesn't mean it can't be done of course!). As an example, let's try
to implement complex numbers as an abstract type.
This is a quick (late night) implementation of an idea I got,
I think it has reasonable overhead. It is heavyweight for
something as simple as a complex number, but maybe reasonable
for something more complex. (I think that the cost of a small
function is ok)
Here I am giving full access to the cadd function on purpose,
it would have been easier to provide accessor functions, but
I thought this is a more intresting excercise.
Btw, this is still not safe against someone who is actively
trying to cheat, but as I use Lua embedded in my application
for me it is more important how Lua secures datatypes implemented
with userdata. I think that is something which appears to be built
nicely into the language + implementation.
(The cheating could be blocked with extra code, and some overhead,
I think)
Eero
-------------
function cpack()
local key={};
complex=function(r,i)
local v={
real=r;
imag=i;
}
return (
function(k)
if k==key then
return v;
else
error("bad access");
end
end
);
end
cadd=function(x,y)
local tx=x(key);
local ty=y(key);
return complex(tx.real+ty.real,tx.imag+ty.imag);
end
real=function(x)
return x(key).real;
end
imag=function(x)
return x(key).imag;
end
end
cpack()
x=complex(1,2);
y=complex(3,7);
z=cadd(x,y);
print(real(z)," ",imag(z));
------------
- References:
- Lua5.0 new "For" question, Peter Hill
- Re: Lua5.0 new "For" question, Björn De Meyer
- Re: Lua5.0 new "For" question, Peter Hill
- Re: Lua5.0 new "For" question, Vincent Penne
- Re: Lua5.0 new "For" question, Peter Hill
- Re: Lua5.0 new "For" question, Björn De Meyer
- Re: Lua5.0 new "For" question, Eero Pajarre
- Re: Lua5.0 new "For" question, Björn De Meyer
- Re: Lua5.0 new "For" question, Eero Pajarre
- Re: Lua5.0 new "For" question, Peter Hill