Test if Lua number is integer or float

这一生的挚爱 提交于 2020-01-03 01:58:26

问题


In my C++ program, I need to know if a Lua variable is an integer number or a floating-point number. The C API provides lua_isnumber() but this function does not distinguish between int/float/double.

So far I have worked around this by using modf():

if (lua_isnumber(luaCtx, -1)) // int / unsigned int / float:
{
    luaVarName = lua_tostring(luaCtx, -2);
    double n = static_cast<double>(lua_tonumber(luaCtx, -1));

    // Figure out if int or float:
    double fractPart, intPart;
    fractPart = modf(n, &intPart);

    if (fractPart != 0.0)
    {
        luaVarType = ScriptVar::TypeTag::Float;
        luaVarData.asFloat = static_cast<float>(n);
    }
    else
    {
        luaVarType = ScriptVar::TypeTag::Integer;
        luaVarData.asInteger = static_cast<int>(n);
    }
}

Does the Lua API provide a way to infer the variable type more precisely?


回答1:


double n = lua_tonumber(L, -1);
if (n == (int)n) {
    // n is an int
} else {
    // n is a double
}

What this code does is just checking if n has any decimals or not. If n is 1.5, then casting it to int ((int)n) will floor the value to 1, so:

1.5 == 1 is false, n is a double

But if n is lets say 4:

4 == 4 is true, n is a int

This works because to lua, the only numeric number that exist is double. So when converting a number from lua to C, we can choose to use int if the number is a integer(whole number).



来源:https://stackoverflow.com/questions/25196042/test-if-lua-number-is-integer-or-float

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!