lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Martin Doering wrote:

> How do you shift with floats??? Do you convert them to
> ints, shift, and convert them back?

I'm not really addressing the larger issue of making Lua aware of an int
type, but I saw this conversation and thought I would toss in the
following.  Lua guru's will probably yawn, but maybe this might help
someone.  Hey, I'm new with the language, but having a great time working
with Lua.  This by the way is for Lua 4.0.

I needed to have some of the integer operators of C in my Lua code, so I
wrote the following.  The Lua macro luaL_check_int casts the LUA_NUM_TYPE
(normally double) into an integer.  Sending back, lua_pushnumber will
coerce the integer result of these operations into a LUA_NUM_TYPE.

#include <stdlib.h>


#include "lauxlib.h"
#include "lua.h"
#include "lualib.h"

#define DYADIC(name, op) \
    static void name(lua_State* L) { \
        lua_pushnumber(L, luaL_check_int(L, 1) op luaL_check_int(L, 2)); \

#define MONADIC(name, op) \
    static void name(lua_State* L) { \
        lua_pushnumber(L, op luaL_check_int(L, 1)); \

DYADIC(intMod,      % )
DYADIC(intAnd,      & )
DYADIC(intOr,       | )
DYADIC(intXor,      ^ )
DYADIC(intShiftl,   <<)
DYADIC(intShiftr,   >>)
MONADIC(intBitNot,  ~ )

static const struct luaL_reg intMathLib[] = {
    {"mod",    intMod    },
    {"band",   intAnd    },
    {"bor",    intOr     },
    {"bxor",   intXor    },
    {"bnot",   intBitNot },
    {"shiftl", intShiftl },
    {"shiftr", intShiftr },

void lua_intMathLibOpen (lua_State *L) {
    luaL_openl(L, intMathLib);