3

Lua 5.3 deprecates luaL_checkint, luaL_checklong, luaL_optint, luaL_optlong, which were just convenience macros calling luaL_{check|opt}integer.

While we can still use them (because of -DLUA_COMPAT_5_2), they aren't mentioned in the user manual and we're advised to use luaL_{check|opt}integer "with a type cast".

Now, I'm not an expert in C and I was wondering:

  1. Is a cast needed in simple cases like the following?

    int i;
    i = (int)luaL_checkinteger(L, 1);
    
  2. If a cast isn't needed here, where is it needed?

  3. Why were those deprecated macros born in the first place if we can do without them? In other words: what did they serve?

  4. Aren't we losing "documentation" by not having the words "int"/"long" embedded in the function name?

greatwolf
  • 20,287
  • 13
  • 71
  • 105
Niccolo M.
  • 3,363
  • 2
  • 22
  • 39

1 Answers1

1
  1. C does not require such a cast.

  2. Basically, if you want the number to behave exactly like a specific C type, then you should cast it to one. If you're fine with it behaving like a lua_Integer, then you do not need to cast it.

    So if you want the range of the value to be within the range of int, then you should cast it when you pull the integer out of Lua. If you try to pass it to a variadic function like printf without the cast, it will get the full range of the lua_Integer, rather than the range of int. That may be what you want, but if it isn't, you need the cast.

  3. They were added because pre-Lua 5.3 numbers were always doubles. As such, to get an integer of any kind required a cast. It's better to cast from double to int directly than from double to long to int. Once Lua formally got an exact integer type, that need became less important.

    Notice that there was never a lua_checkfloat. The same reason applies.

  4. That's open to interpretation. But since integers are first-class values in Lua 5.3, I'd say it's better to be able to fetch the integer exactly as Lua sees it. If the user wants to cast it to a different integer type, that's up to them.

    As for being better documentation, this isn't C++11. There's no auto x = lua_checkinteger(...); here. The type you're using must be explicitly stated when you're using it. If you're assigning it to a variable, it is clear to all what you are doing. If you're explicitly casting it, then again it's clear what you're doing. If you're passing it to a function, all you need do is look at the argument list to see what it is being converted into.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982