2

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?

2
  • 3
    Nope. You can cast it to an unsigned type using lua_tounsigned or lua_checkunsigned. Otherwise you have to cast it like you have. Commented Aug 8, 2014 at 4:33
  • 2
    Lua 5.3 will have both integer and floating point types. Commented Aug 8, 2014 at 5:23

2 Answers 2

7
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).

Sign up to request clarification or add additional context in comments.

2 Comments

This answer is up for deletion. Its hard to tell if this is a quality answer. Could you explain it a bit?
OK, so no extra info about numbers, you have to check it yourself. Easy enough with a type cast / floor(), etc.
1

This is a very old post, but for anyone searching for it. There is a simple way to do this in C++ as of Lua 5.3

if (lua_isinteger(L, -1)) { // Available in Lua 5.3 and above
    // Value on stack is an integer. Eg. 5
} else {
    // Value on stack is a double. Eg. 12.53
}

This way checks if the value was initialised as a integer or not in the lua code. For example:

val = 1.0 -- This would be seen as a double, not an integer
var = 1 -- This would be seen as an integer

Even though both values are the same they have different types. this is recognised by lua_isinteger. While val == (int)val only detects if the number is a whole number

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.