lua-users home
lua-l archive

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


> Talking about the 'simple modification in luaconf.h' I'm wondering if
> you can really add support for complex number so easily.

It was not too hard, but I did not test it very much:

> I=math.I
> =I
0+1i
> =I*I
-1+0i
> =I^2
-1+1.2246063538224e-16i

Adding complex numbers to the core was pretty easy. You just need to
edit luaconf.h: (I took the easy way out in number comparison: I compare
real parts only.)

diff /tmp/lhf/lua-5.2.0-work2/src/luaconf.h ./luaconf.h
12a13
> #include <complex.h>
364,365c365
< #define LUA_NUMBER_DOUBLE
< #define LUA_NUMBER	double
---
> #define LUA_NUMBER	double complex
382,383c382,383
< #define LUA_NUMBER_FMT		"%.14g"
< #define lua_number2str(s,n)	sprintf((s), LUA_NUMBER_FMT, (n))
---
> #define LUA_NUMBER_FMT		"%.14g%+.14gi"
> #define lua_number2str(s,n)	sprintf((s), LUA_NUMBER_FMT, creal(n),cimag(n))
396c396
< #define luai_numpow(L,a,b)	(pow(a,b))
---
> #define luai_numpow(L,a,b)	(cpow(a,b))
407,408c407,408
< #define luai_numlt(L,a,b)	((a)<(b))
< #define luai_numle(L,a,b)	((a)<=(b))
---
> #define luai_numlt(L,a,b)	(creal(a)<creal(b))
> #define luai_numle(L,a,b)	(creal(a)<=creal(b))

You need to ask for C99 in the Makefile:

diff /tmp/lhf/lua-5.2.0-work2/src/Makefile ./Makefile
7c7
< PLAT= none
---
> PLAT= generic
10c10
< CFLAGS= -O2 -Wall $(MYCFLAGS)
---
> CFLAGS= -std=c99 -O2 -pedantic -Wall $(MYCFLAGS)

The libraries gave more trouble but not too much. Here's the easy way out:

diff /tmp/lhf/lua-5.2.0-work2/src/liolib.c ./liolib.c
314c314
<   lua_Number d;
---
>   double d;
458c458
<           fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
---
>           fprintf(f, LUA_NUMBER_FMT, (double)lua_tonumber(L, arg)) > 0;

diff /tmp/lhf/lua-5.2.0-work2/src/lmathlib.c ./lmathlib.c
172c172
<     if (d < dmin)
---
>     if (creal(d) < creal(dmin))
186c186
<     if (d > dmax)
---
>     if (creal(d) > creal(dmax))
197c197
<   lua_Number r = (lua_Number)(rand()%RAND_MAX) / (lua_Number)RAND_MAX;
---
>   double r = (lua_Number)(rand()%RAND_MAX) / (lua_Number)RAND_MAX;
204c204
<       lua_Number u = luaL_checknumber(L, 1);
---
>       double u = luaL_checknumber(L, 1);
210,211c210,211
<       lua_Number l = luaL_checknumber(L, 1);
<       lua_Number u = luaL_checknumber(L, 2);
---
>       double l = luaL_checknumber(L, 1);
>       double u = luaL_checknumber(L, 2);
270a271,272
>   lua_pushnumber(L, I);
>   lua_setfield(L, -2, "I");

diff /tmp/lhf/lua-5.2.0-work2/src/lstrlib.c ./lstrlib.c
809c809
<           lua_Number n = luaL_checknumber(L, arg);
---
>           double n = luaL_checknumber(L, arg);