3

Should I use lua_tointeger(), or lua_tonumber(), when converting Lua numbers to off_t values?

I checked the source code of Lua itself and I see that their file:seek function uses lua_Number, not lua_Integer.

I also see that the luaposix package uses lua_tonumber() (or luaL_checknumber() etc) extensively, even to read file decriptors(!).

And what about size_t?

Should I go to the "extreme" and use lua_tonumber() (and lua_pushnumber()) for all integral C types (mode_t, size_t, etc.)? Or should I normally use lua_tointeger() and resort to lua_tonumber() only when I "feel" it's a potentially big number?

Niccolo M.
  • 3,363
  • 2
  • 22
  • 39
  • 1
    Please, always link to the correct source. You linked to the Battle for Wesnoth code, not the [original Lua `file:seek` implementation](http://www.lua.org/source/5.2/liolib.c.html#f_seek). They happen to be the same, but you never know in the future. – LorenzoDonati4Ukraine-OnStrike Oct 01 '13 at 08:19

2 Answers2

2

Since off_t and size_t are both integral types, you should use lua_tointeger.

From the source, lua_tointeger actually gets the number as lua_Number, then converts it to lua_Integer. The only concern is that lua_Integer may be too small, but as it's implemented as ptrdiff_t which in practice is usually 32-bit on 32-bit machine and 64-bit on 64-bit machine.

Community
  • 1
  • 1
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
1

If you build Lua yourself you can check in luaconf.h how lua_Number and lua_Integer are defined. Usually lua_number is the same thing as double and lua_Integer is ptrdiff_t.

ptrdiff_t (usually int32_t or int64_t) is closer to off_t (uint32_t or uint64_t) than double but Lua will probably store the number in double format anyway.

On the other hand double can store integers precisely up to 2^52 if I remember correctly. In most cases it should be sufficient.

I would suggest using lua_*number() where you expect float/double and lua_*integer() when you expect integers (like all those OS related functions with FDs, offsets and positions).

Caladan
  • 1,471
  • 11
  • 13