lua-users home
lua-l archive

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


Luiz Henrique de Figueiredo wrote:
> > > The only way out that I can see is to use an explicit block as in say
> > > 	complex.enter()
> > > 	complex.eval(a * exp(i*z) + b, a*b+z)
> > > 	complex.exit()
> >
> > Would you care to explain how you can get the above to work?  I thought
> > maybe you mean that inside the block, everything is temporary, but I'm not
> > sure that would work.
> 
> Yes, I mean that inside the block, everything is temporary and stored
> in static vars in C. The complex C library would have 256 static
> pointers to hold temporary userdata, say allocated at the start in
> luaopen_complex. complex.enter would start using them instead of
> allocating new ones. The expressions in complex.eval would be evaluated
> as usual by Lua, but using the temporary userdata. However, complex.eval
> would duplicate the userdata corresponding to its arguments, using real
> allocation, so that they can be returned. I should have written
> 	val1, val2 = complex.eval(a * exp(i*z) + b, a*b+z)
> 
> complex.exit would clear the internal counter. Perhaps it is not needed
> and this can be done in complex.eval, but it seems clear to explicitly
> bracket blocks.

One way of doing this in Numlua 0.3 is to use the optional "in-place" argument
to complex functions:

> c = complex(1,2)
> print(c:exp(), c) -- returns new complex
-1.1312043837568+2.4717266720048i 1+2i
> print(c:exp(true), c) -- operates in-place
-1.1312043837568+2.4717266720048i -1.1312043837568+2.4717266720048i

So, one way of implementing f is to use a cache:

-- note: no new complex numbers are created since all ops are in-place
local c, I = complex(), complex.i -- cache
function f (a, b, z)
  -- a * exp(I * z) + b)
  return z:copy(c):mul(I, true):exp(true):mul(a, true):add(b, true)
end

Cheers,
Luis
 

-- 
Computers are useless. They can only give you answers.
                -- Pablo Picasso

-- 
Luis Carvalho (Kozure)
lua -e 'print((("lexcarvalho@NO.gmail.SPAM.com"):gsub("(%u+%.)","")))'