]> git.mxchange.org Git - simgear.git/blob - simgear/nasal/mathlib.c
e20db595bd9974026903887b5c2928d9e4ab553b
[simgear.git] / simgear / nasal / mathlib.c
1
2 #include <math.h>
3 #include <string.h>
4
5 #include "nasal.h"
6
7 static naRef f_sin(naContext c, naRef me, int argc, naRef* args)
8 {
9     naRef a = naNumValue(argc > 0 ? args[0] : naNil());
10     if(naIsNil(a))
11         naRuntimeError(c, "non numeric argument to sin()");
12     a.num = sin(a.num);
13     return a;
14 }
15
16 static naRef f_cos(naContext c, naRef me, int argc, naRef* args)
17 {
18     naRef a = naNumValue(argc > 0 ? args[0] : naNil());
19     if(naIsNil(a))
20         naRuntimeError(c, "non numeric argument to cos()");
21     a.num = cos(a.num);
22     return a;
23 }
24
25 static naRef f_exp(naContext c, naRef me, int argc, naRef* args)
26 {
27     naRef a = naNumValue(argc > 0 ? args[0] : naNil());
28     if(naIsNil(a))
29         naRuntimeError(c, "non numeric argument to exp()");
30     a.num = exp(a.num);
31     return a;
32 }
33
34 static naRef f_ln(naContext c, naRef me, int argc, naRef* args)
35 {
36     naRef a = naNumValue(argc > 0 ? args[0] : naNil());
37     if(naIsNil(a))
38         naRuntimeError(c, "non numeric argument to ln()");
39     a.num = log(a.num);
40     return a;
41 }
42
43 static naRef f_sqrt(naContext c, naRef me, int argc, naRef* args)
44 {
45     naRef a = naNumValue(argc > 0 ? args[0] : naNil());
46     if(naIsNil(a))
47         naRuntimeError(c, "non numeric argument to sqrt()");
48     a.num = sqrt(a.num);
49     return a;
50 }
51
52 static naRef f_atan2(naContext c, naRef me, int argc, naRef* args)
53 {
54     naRef a = naNumValue(argc > 0 ? args[0] : naNil());
55     naRef b = naNumValue(argc > 1 ? args[1] : naNil());
56     if(naIsNil(a) || naIsNil(b))
57         naRuntimeError(c, "non numeric argument to atan2()");
58     a.num = atan2(a.num, b.num);
59     return a;
60 }
61
62 static naCFuncItem funcs[] = {
63     { "sin", f_sin },
64     { "cos", f_cos },
65     { "exp", f_exp },
66     { "ln", f_ln },
67     { "sqrt", f_sqrt },
68     { "atan2", f_atan2 },
69     { 0 }
70 };
71
72 naRef naInit_math(naContext c)
73 {
74     naRef ns = naGenLib(c, funcs);
75     naAddSym(c, ns, "pi", naNum(3.14159265358979323846));
76     naAddSym(c, ns, "e", naNum(2.7182818284590452354));
77     return ns;
78 }