Finding the sign of a Lua number, from C

I have a question that seems trivial.

Let's say there is a number at the top of the Lua stack. I want to know (in C) if this number is positive, negative, or zero.

A naive solution would be:

lua_Number num = lua_tonumber(L, -1);
if (num > 0)
   print("positive")
else if (num < 0)
   print("negative")
else
   print("zero")

      

However, this may not work well in Lua 5.3, because if it is a Lua integer (lua_Integer) on the stack, it may not match our variable num

(which is lua_Number).

So how can I write my C code to work in Lua 5.1 / 5.2 and Lua 5.3?

(By the way, the reason I'm only interested in the sign and not the number itself is because this number is the return value of the comparison function for the sort algorithm. It is the result of comparing two elements.)

+3


source to share


1 answer


One possible solution is to let Lua do the comparison for you. This can be done using lua_compare

(or lua_lessthan

, for LuaJIT and Lua 5.1):



#if LUA_VERSION_NUM == 501
  #define LUA_LESS_THAN(state, index1, index2) lua_lessthan(state, index1, index2)
#elif LUA_VERSION_NUM > 501
  #define LUA_LESS_THAN(state, index1, index2) lua_compare(state, index1, index2, LUA_OPLT)
#endif

lua_pushnumber(L, 0);
if (LUA_LESS_THAN(L, -1, -2)) {
  // 0 < num
} else if (LUA_LESS_THAN(L, -2, -1)) {
  // 0 > num
} else {
  // 0 == num
}
lua_pop(L, 1);

      

+3


source







All Articles