]> git.mxchange.org Git - simgear.git/blob - simgear/nasal/mathlib.c
Version 1.3 of Andy Ross's "NASAL" embedded scripting language.
[simgear.git] / simgear / nasal / mathlib.c
1 #include <math.h>
2 #include <string.h>
3
4 #include "nasal.h"
5
6 static naRef f_sin(naContext c, naRef args)
7 {
8     naRef a = naNumValue(naVec_get(args, 0));
9     if(naIsNil(a))
10         naRuntimeError(c, "non numeric argument to sin()");
11     a.num = sin(a.num);
12     return a;
13 }
14
15 static naRef f_cos(naContext c, naRef args)
16 {
17     naRef a = naNumValue(naVec_get(args, 0));
18     if(naIsNil(a))
19         naRuntimeError(c, "non numeric argument to cos()");
20     a.num = cos(a.num);
21     return a;
22 }
23
24 static naRef f_exp(naContext c, naRef args)
25 {
26     naRef a = naNumValue(naVec_get(args, 0));
27     if(naIsNil(a))
28         naRuntimeError(c, "non numeric argument to exp()");
29     a.num = exp(a.num);
30     return a;
31 }
32
33 static naRef f_ln(naContext c, naRef args)
34 {
35     naRef a = naNumValue(naVec_get(args, 0));
36     if(naIsNil(a))
37         naRuntimeError(c, "non numeric argument to ln()");
38     a.num = log(a.num);
39     return a;
40 }
41
42 static naRef f_sqrt(naContext c, naRef args)
43 {
44     naRef a = naNumValue(naVec_get(args, 0));
45     if(naIsNil(a))
46         naRuntimeError(c, "non numeric argument to sqrt()");
47     a.num = sqrt(a.num);
48     return a;
49 }
50
51 static naRef f_atan2(naContext c, naRef args)
52 {
53     naRef a = naNumValue(naVec_get(args, 0));
54     naRef b = naNumValue(naVec_get(args, 1));
55     if(naIsNil(a) || naIsNil(b))
56         naRuntimeError(c, "non numeric argument to atan2()");
57     a.num = atan2(a.num, b.num);
58     return a;
59 }
60
61 static struct func { char* name; naCFunction func; } funcs[] = {
62     { "sin", f_sin },
63     { "cos", f_cos },
64     { "exp", f_exp },
65     { "ln", f_ln },
66     { "sqrt", f_sqrt },
67     { "atan2", f_atan2 },
68 };
69
70 naRef naMathLib(naContext c)
71 {
72     naRef name, namespace = naNewHash(c);
73     int i, n = sizeof(funcs)/sizeof(struct func);
74     for(i=0; i<n; i++) {
75         naRef code = naNewCCode(c, funcs[i].func);
76         naRef name = naStr_fromdata(naNewString(c),
77                                     funcs[i].name, strlen(funcs[i].name));
78         naHash_set(namespace, name, naNewFunc(c, code));
79     }
80
81     // Set up constants for math.pi and math.e
82     name = naStr_fromdata(naNewString(c), "pi", 2);
83     naHash_set(namespace, name, naNum(M_PI));
84
85     name = naStr_fromdata(naNewString(c), "e", 1);
86     naHash_set(namespace, name, naNum(M_E));
87
88     return namespace;
89 }