aboutsummaryrefslogtreecommitdiff
path: root/src/lua/bit/luaopen_bit.cpp
blob: 3b086bbecd2d2f6d2b70998a77fbbcbf8e843d22 (plain)
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
#include "lua/luax.h"
#include "libjin/jin.h"
#include <cstdlib>

namespace jin
{
namespace lua
{

    static int l_and(lua_State* L)
    {
        int a = luax_checkinteger(L, 1);
        int b = luax_checkinteger(L, 2);
        luax_pushinteger(L, a & b);
        return 1;
    }

    static int l_or(lua_State* L)
    {
        int a = luax_checkinteger(L, 1);
        int b = luax_checkinteger(L, 2);
        luax_pushinteger(L, a | b);
        return 1;
    }

    static int l_xor(lua_State* L)
    {
        int a = luax_checkinteger(L, 1);
        int b = luax_checkinteger(L, 2);
        luax_pushinteger(L, a ^ b);
        return 1;
    }

    static int l_not(lua_State* L)
    {
        int n = luax_checkinteger(L, 1);
        luax_pushinteger(L, ~n);
        return 1;
    }

    static int l_lshift(lua_State* L)
    {
        int a = luax_checkinteger(L, 1);
        int b = luax_checkinteger(L, 2);
        luax_pushinteger(L, a << b);
        return 1;
    }

    static int l_rshift(lua_State* L)
    {
        int a = luax_checkinteger(L, 1);
        int b = luax_checkinteger(L, 2);
        luax_pushinteger(L, a >> b);
        return 1;
    }

    static int l_include(lua_State* L)
    {
        int a = luax_checkinteger(L, 1);
        int b = luax_checkinteger(L, 2);
        luax_pushboolean(L, (a & b) == b);
        return 1;
    }

    static const luaL_Reg f[] = {
        { "bAnd", l_and     },
        { "bOr" , l_or      },
        { "bXor", l_xor     },
        { "bNot", l_not     },
        { "bLs",  l_lshift  },
        { "bRs",  l_rshift  },
        { "bInc", l_include },
        { 0,      0         }
    };

    int luaopen_bit(lua_State* L)
    {
        luax_newlib(L, f);

        return 1;
    }

}
}