lua-users home
lua-l archive

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


I'm one of the developers/maintainers of a certain (open source) game port and one of our upcoming ideas is to replace the existing scripting language with something based on Lua; more specifically LuaJIT because of its efficiency and the fact that we mostly target x86/x64 anyway.

From reading the documentation, it looks like LuaJIT's FFI is the perfect tool for making engine and game functions/structures accessible from the scripting language, where of course only "safe" functions should be made visible directly (for example, those taking only scalar numbers). But as far as I can see, the FFI docs don't specify what happens for numeric conversions that are undefined per C standard, such as downcasting a number greater than INT_MAX to an int.

A few experiments with the following C function

    void printint(int x) { printf("%d\n",x); }

give these results from LuaJIT for me:

    printint(2147483648+1)  --> -2147483648
    printint(4*2147483648)  --> -2147483648
    printint(-2147483648-1)  --> -2147483648
    printint(0/0)  --> -2147483648
    printint(1/0)  --> -2147483648

So, in every "interesting" case, the out-of-range double is apparently converted to INT_MIN, but can I rely on this or is this a coincidental side-effect of the implementation?

The closest thing to an answer I could find is the "Conversion between C types" section in the FFI documentation: ,
but again I'm not sure what to make of the undefined cases here. For example, the double to int conversion is listed as

    double -->^trunc int,

but what is "truncation" supposed to mean in this particular context? It can't conceptually mean "round the double to an infinite-precision integer and take its 32 lowest-order bits", since it would be undefined for inf/nan and it's inconsistent with my experimental findings.