-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnumber.go
61 lines (53 loc) · 1.17 KB
/
number.go
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
package glua
/*
#include "c/glua.h"
*/
import "C"
import (
"strconv"
"golang.org/x/exp/constraints"
)
const LUA_NUMBER_MAX_SAFE_INTEGER int64 = (2 ^ 53) - 1
func pushNumber(L State, n LUA_NUMBER) {
C.lua_pushnumber_wrap(L.c(), C.double(n))
}
func pushInt[V constraints.Integer](L State, n V) {
// max(-n, n) is a quick way to get the absolute value of n, since golang doesn't have a built-in abs function for integers :D
if max(-n, n) <= V(LUA_NUMBER_MAX_SAFE_INTEGER) {
pushNumber(L, LUA_NUMBER(n))
} else {
if n < 0 {
L.PushString(strconv.FormatInt(int64(n), 10))
} else {
L.PushString(strconv.FormatUint(uint64(n), 10))
}
}
}
func (L State) PushNumber(n any) {
switch v := n.(type) {
case int:
pushInt(L, v)
case int8:
pushNumber(L, LUA_NUMBER(v))
case int16:
pushNumber(L, LUA_NUMBER(v))
case int32:
pushNumber(L, LUA_NUMBER(v))
case int64:
pushInt(L, v)
case uint:
pushInt(L, v)
case uint8:
pushNumber(L, LUA_NUMBER(v))
case uint16:
pushNumber(L, LUA_NUMBER(v))
case uint32:
pushNumber(L, LUA_NUMBER(v))
case uint64:
pushInt(L, v)
case float32:
pushNumber(L, LUA_NUMBER(v))
case float64:
pushNumber(L, LUA_NUMBER(v))
}
}