问题
I need to save a list of lua float nubers in byte form and attach that to a string. I know string.pack exists for Lua 5.3 but I'm limited to Luajit. I'm not too familiar with FFI and I'd appreciate help on using it if it has a solution ( using tostring(number) just uses way too many bytes for numbers and memory is limited )
Basically, I need a way to get a binary string packed form of a list of numbers (floats for now), using Luajit, and be able to store it in a string & concat that string to another string and even write things after it (I got trouble with this one in 5.3, so not sure if it's possible in whatever solution you suggest to me below)
Also, if done correctly, is it possible that I use regex on the obtained string? it would be extremely handy for me.
I can't use lua 5.3 as an alternative mainly because of performance. Luajit is way faster and more suitable for the application I'm using it for (cough training neural networks)
And of course, when I need string.pack, I need string.unpack.
回答1:
How to pack array of numbers to a binary string:
-- convert t to str
local t = {1/3, 1/7, 3/5} -- array of floating point numbers
local str = ffi.string(ffi.new("float[?]", #t, t), 4 * #t)
How to unpack binary string to array of numbers:
-- convert str to t
local ptr = ffi.cast("float*", ffi.new("char[?]", #str, str))
local t = {}
for _ = 1, #str / 4 do
t[#t + 1] = ptr[#t]
end
For 8-byte doubles, replace float
with double
and 4
with 8
回答2:
You may want to check if lua-pack or lua-struct already do what you need.
来源:https://stackoverflow.com/questions/50807140/luajit-equivalent-for-string-pack-and-string-unpack