lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

>In any case, how do I open a file in binary and write binary data to it? (I don''t want my numbers converted to strings, as that's what seems to be happening)

You open the file with openfile(name,"wb"), as you already know ("w+b" if you
want to append instead of overwriting).
To write binary data, you could in principle use strchar(byte) as Pedro Miller
suggested, but that assumes that you know how to break your binary data into
bytes. For integers, it's simple with a sequence of divisions by 256 (or
you could use "%08X" in format and then write strchar(byte) of each 2 hex
digits). For numbers with fractional part, it's harder, but you may get by
by using frexp. You might prefer to write a simple library that does this for
you. Something like this (untested!):

static tobinary(lua_State* L)
 if arg is number then
  void* u=lua_newuserdata(L,sizeof(double));
  double x=lua_tonumber(L,1));
 else if arg is string
  ; /* do nothing */
 return 1;

and export this to Lua. Then you'd simply do write(tobinary(x)) in Lua.