Why does lua_tonumber () have a different behavior from lua_tointeger () when dealing with a large integer?

I tried converting a string from Lua (5.1.5) to an integer and checking if the number is a real integer (0 ~ 99999). However, I found that lua_tonumber () has a different behavior from lua_tointeger () when dealing with a large integer.

int main() { int in; double db; lua_State* Lua = luaL_newstate(); luaL_openlibs(Lua); lua_pushstring(Lua, "213232127162767162736718238168263816873"); db = lua_tonumber(Lua, -1); in = lua_tointeger(Lua, -1); printf("DOUBLE:%f\n", db); // DOUBLE:213232127162767176000119210017101447168.000000 printf("INT:%d\n", in); // INT:0 }; 

If I use lua_tointeger (), it returns 0 and will conduct my check.

I check both API descriptions, but I still don't know why they have different types of behavior. Are these behaviors independent of the machine? Does lua_tonumber () use the best way?

Can I use the following code to check the result? (Cross platform)

 if (!lua_isnumber(Lua, -1)) { //error } result = lua_tonumber(Lua, -1); if (result < 0 || result > 99999) { // error2 } // pass 
+6
source share
1 answer

From the lua_tointeger help reference:

Converts a Lua value with a given valid index to the signed integral type lua_Integer . The Lua value must be a number or a string convertible to a number (see Clause 2.2.1); otherwise lua_tointeger returns 0

Same thing with lua_tonumber . Therefore, when you get the return value of 0 , you pass a string that is not convertible. The number 213232127162767162736718238168263816873 too large for lua_Integer (same as ptrdiff_t by default).

Are these behaviors independent of the machine? Does lua_tonumber () use the best way?

In a sense, it is machine dependent, because the lua_Integer type is lua_Integer dependent. Again, the number 213232127162767162736718238168263816873 too large for any normal integer type. Using lua_tonumber or using lua_tointeger depends on your needs. If you convert an integer that is less than 32 bits, for example 0 ~ 99999 to your question, lua_tointeger is your choice. It runs very quickly on an IEEE-754 compatible machine. The downside of using lua_tonumber is that it may not properly convert non-integer values.

Link: A quick method to round to a 32-bit int

+4
source

Source: https://habr.com/ru/post/953137/


All Articles