-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlrand.c
98 lines (83 loc) · 1.98 KB
/
lrand.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <math.h>
#include "lua.h"
#include "lauxlib.h"
#define MYNAME "lrand"
#define MYVERSION MYNAME " library for " LUA_VERSION
#define MYTYPE MYNAME "_state"
#define SEED 1794ULL
#include "mt19937-64.c"
static MT *Pget(lua_State *L, int i) {
return luaL_checkudata(L, i, MYTYPE);
}
static MT *Pnew(lua_State *L) {
MT *c= lua_newuserdata(L, sizeof(MT));
luaL_getmetatable(L, MYTYPE);
lua_setmetatable(L, -2);
return c;
}
//new([seed])
static int Lnew(lua_State *L) {
lua_Integer seed = luaL_optinteger(L, 1, SEED);
MT *c = Pnew(L);
init_genrand64(c, seed);
return 1;
}
//clone(c)
static int Lclone(lua_State *L) {
MT *c=Pget(L,1);
MT *d=Pnew(L);
*d=*c;
return 1;
}
static int Lseed(lua_State *L) {
MT *c = Pget(L,1);
init_genrand64(c,luaL_optinteger(L,2,SEED));
lua_settop(L,1);
return 1;
}
static int Lrandu64(lua_State *L) {
MT *c = Pget(L, 1);
lua_pushinteger(L, genrand64_int64(c));
return 1;
}
static int Lrandi64(lua_State *L) {
MT *c = Pget(L, 1);
lua_pushinteger(L, genrand64_int63(c));
return 1;
}
static int Lrandd(lua_State *L) {
MT *c = Pget(L, 1);
lua_pushnumber(L, genrand64_real1(c));
return 1;
}
static int Ltostring(lua_State *L)
{
MT *c=Pget(L,1);
lua_pushfstring(L,"%s %p",MYTYPE,(void*)c);
return 1;
}
static const luaL_Reg R[] = {
{"__tostring", Ltostring},
{"clone", Lclone},
{"new", Lnew},
{"seed", Lseed},
{"randu64", Lrandu64},
{"randi64", Lrandi64},
{"randd", Lrandd},
{NULL, NULL}
};
LUALIB_API int luaopen_lrand(lua_State *L) {
luaL_newmetatable(L,MYTYPE);
luaL_setfuncs(L, R, 0);
lua_pushliteral(L,"version"); /** version */
lua_pushliteral(L,MYVERSION);
lua_settable(L,-3);
lua_pushliteral(L,"__index");
lua_pushvalue(L,-2);
lua_settable(L,-3);
lua_pushliteral(L,"__call"); /** __call(c) */
lua_pushliteral(L,"randu64");
lua_gettable(L,-3);
lua_settable(L,-3);
return 1;
}