Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua C api: handling large numbers

Tags:

c

lua

I deal with picoseconds in my code (numbers are > 10^12).
C code to pass data to Lua (atime and eventid are both of size_t type)

lua_getglobal ( luactx, "timer_callback" );
lua_pushunsigned ( luactx, atime );
lua_pushunsigned ( luactx, eventid );
lua_pcall ( luactx, 2, 0, 0 );

Lua function

function timer_callback(time, eventid)  
  if eventid == TX_CLOCK then
  out_log(tostring(time)) --result is random garbage
  set_callback(time + 1000000000000, TX_CLOCK)
  return
  end  
end

I tried with lua_pushnumber but in result in lua I got negative numbers.

like image 967
pugnator Avatar asked Sep 23 '14 16:09

pugnator


1 Answers

Lua, as of 5.3, supports lua_Integer, which is 64 bits by default. From the reference manual:

lua_Integer

typedef ... lua_Integer;

The type of integers in Lua.

By default this type is long long (usually a 64-bit two-complement integer), but that can be changed to long or int, usually a 32-bit two-complement integer. (See LUA_INT in luaconf.h.) Lua also defines the constants LUA_MININTEGER and LUA_MAXINTEGER, with the minimum and the maximum values that fit in this type.

Lua 5.2 lua can be coerced into using a different number type fairly easily by editing luaconf.h. The number type is defined as LUA_NUMBER.

For lua 5.1, you can install the lnum patch, which will change the integer type.

like image 148
indiv Avatar answered Oct 07 '22 02:10

indiv