2
votes

I have a file I opened as binary like this: local dem = io.open("testdem.dem", "rb")
I can read out strings from it just fine: print(dem:read(8)) -> HL2DEMO, however, afterwards there is a 4-byte little endian integer and a 4-byte float (docs for the file format don't specify endianess but since it didn't specify little like the integer I'll have to assume big). This cannot be read out with read. I am new to the LuaJIT FFI and am not sure how to read this out. Frankly, I find the documentation on this specific aspect of the FFI to be underwhelming, although I'm just a lua programmer and don't have much experience with C. One thing I have tried is creating a cdata, but I don't think I understand that:

local dem = io.open("testdem.dem", "rb")
print(dem:read(8))
local cd = ffi.new("int", 4)
ffi.copy(cd, dem:read(4), 4)
print(tostring(cd))
--[[Output
HL2DEMO
luajit: bad argument #1 to 'copy' (cannot convert 'int' to 'void *')
]]--

Summary:
Goal: Read integers and floats from binary data.
Expected output: A lua integer or float I can then convert to string.

1
You could also take this as an excuse to learn C and implement your own version of 5.3s string.unpack function ;) - DarkWiiPlayer
I have indeed pivoted to trying to learn C for this program, as even though the FFI solved my problem, I found it frustrating to try and create standalone executables with linked dependencies with LuaJIT/Lua. My new problem is that C sucks! Very unfun to learn and write. - Allister

1 Answers

3
votes

string.unpack does this for Lua 5.3, but there are some alternatives for LuaJIT as well. For example, see this answer (and other answers to the same question).