c - 为什么 lua_tonumber() 在处理大整数时与 lua_tointeger() 有不同的行为?

标签 c lua

我尝试将字符串从 Lua(5.1.5) 转换为整数,并检查该数字是否为有效整数(0~99999)。但是,我发现 lua_tonumber() 在处理大整数时与 lua_tointeger() 有不同的行为。

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
};

如果我使用 lua_tointeger(),它会返回 0 并通过我的检查。

我检查了两个 API 的描述,但我仍然不知道为什么它们有不同的行为。这些行为是否与机器无关?使用 lua_tonumber() 是更好的方法吗?

我可以使用下面的代码来检查结果吗? (跨平台)

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

最佳答案

来自 lua_tointeger 的手册引用:

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

lua_tonumber 也是如此。因此,当您获得 0 的返回值时,意味着您正在传递一个不可转换的字符串。数字 213232127162767162736718238168263816873 对于 lua_Integer(默认情况下与 ptrdiff_t 相同)类型来说太大了。

Are these behaviors machine-independent? Is using lua_tonumber() a better way?

在某种程度上,它是机器相关的,因为 lua_Integer 类型是机器相关的。同样,数字 213232127162767162736718238168263816873 对于任何普通整数类型来说都太大了。使用lua_tonumber 还是使用lua_tointeger 取决于您的需要。如果转换一个小于 32 位的整数,例如你问题中的 0~99999,lua_tointeger 是你的选择。它在 IEEE-754 兼容机器中非常快。使用 lua_tonumber 的缺点是它可能会错误地转换非整数值。

引用:A fast method to round a double to a 32-bit int explained

关于c - 为什么 lua_tonumber() 在处理大整数时与 lua_tointeger() 有不同的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18609305/

相关文章:

c - 变量 "carry"周围的堆栈已损坏

c - 在C中将数学方程插入二叉树

c - x86内核中的键盘IRQ

api - 如何在Lua中创建表,然后从C API添加值?

c - 中间件:使用 C 作为引擎,Lua 作为适配器……这是不好的做法(安全风险)吗?

path - vlc lua : how do I get the full path of the current playing item?

c - 链表 : count=count->next gives segmentation fault

c - 如何在linux中打印时间

arrays - Lua 不会超过表中的 'nil'

lua - 嵌入lua时如何设置 "require"路径?