luastring.formatlua-5.3

How to print lld in Lua 5.3


string.format (formatstring, ···)

Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string). The format string follows the same rules as the ISO C function sprintf. The only differences are that the options/modifiers *, h, L, l, n, and p are not supported and that there is an extra option, q.

Lua 5.3 doesn't support lld, how can I print lld in Lua 5.3?


Solution

  • Short answer: use %d.


    In C sprintf, %lld is used to format a long long type, which is an integer type at least 64 bit.

    In Lua 5.3, the type number has two internal representations, integer and float. Integer representation is 64-bit in standard Lua. You can use %d to print it no matter its internal representation:

    print(string.format("%d", 2^62))
    

    Output: 4611686018427387904


    In Lua source file luaconf.h, you can see that Lua converts %d to the approapriate format:

    #define LUA_INTEGER_FMT     "%" LUA_INTEGER_FRMLEN "d"
    

    and LUA_INTEGER_FRMLEN is defined as "", "l" or "ll" if different internal representation for integer is used:

    #if defined(LLONG_MAX)      /* { */
    /* use ISO C99 stuff */
    #define LUA_INTEGER     long long
    #define LUA_INTEGER_FRMLEN  "ll"
    //...