测试Lua号是整数还是浮点数 [英] Test if Lua number is integer or float
问题描述
在我的C ++程序中,我需要知道Lua变量是整数还是浮点数. C API提供了lua_isnumber()
,但是此功能不能区分int/float/double
.
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
.
到目前为止,我已经通过使用modf()
来解决此问题:
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);
}
}
Lua API是否提供一种更精确地推断变量类型的方法?
Does the Lua API provide a way to infer the variable type more precisely?
推荐答案
double n = lua_tonumber(L, -1);
if (n == (int)n) {
// n is an int
} else {
// n is a double
}
此代码的作用只是检查n是否有小数. 如果n为1.5,则将其强制转换为int((int)n)会将值底限为1,因此:
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为假,n为双精度
1.5 == 1 is false, n is a double
但是,如果n为4:
4 == 4为真,n为整数
4 == 4 is true, n is a int
之所以起作用,是因为lua唯一存在的数字是double.因此,当将数字从lua转换为C时,如果数字是整数(整数),我们可以选择使用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).
这篇关于测试Lua号是整数还是浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!