2

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.

2
  • You could also take this as an excuse to learn C and implement your own version of 5.3s string.unpack function ;) Commented May 4, 2020 at 11:30
  • 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. Commented May 4, 2020 at 17:11

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I did do searching before but I could not find an answer on SO, probably because the title is not closely related to my issue.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.