我想在Lua中编写"映射"而不是在C中编写Lua的简单和美丽;-)
所以我们可以说在CI中可能有以下内容:
typedef struct my_struct{
char field_1[10];
char field_2[250];
char field_3[2000];
}my_struct;
my_struct *pmy_struct;
pmy_struct = (my_struct *) some_buffer;
Run Code Online (Sandbox Code Playgroud)
因此,我想在Lua中使用一种方式在"结构"内的字段上具有固定长度,以便整个BUFFER OFFSETS在到达目标系统时保持一致....
所以让我们在上面的结构中说我想将"field_3"设置为文本"apple"......我仍然希望该结构字段的总长度为2000字节...
你可以用Lua做到这一点.
如果您希望(或被迫)继续使用Lua 5.1,请考虑使用结构库.
raw_data = struct.pack("c10c250c2000", field1, field2, field3)
field1, field2, field3 = struct.unpack("c10c250c2000", raw_data)
Run Code Online (Sandbox Code Playgroud)
但是,目前最好的解决方案是LuaJIT ; 使用LuaJIT比标准的Lua实现有很多好处,但最适用于你的是FFI库.
local ffi = require"ffi"
ffi.cdef[[
typedef struct {
char field_1[10];
char field_2[250];
char field_3[2000];
} my_struct;
]]
local my_thing = ffi.new("my_struct")
my_thing.field_1 = "Ain't"
my_thing.field_2 = "this"
my_thing.field_3 = "great? :D"
local ptr_my_thing = ffi.new("my_struct*", my_thing)
ptr_my_thing.field_2 = [[
LuaJIT does a great job at figuring out
what you're trying to do.
]]
ptr_my_thing.field_3 = [[
There are some cases where the generics of
Lua cannot be used to infer information,
so have a look at the LuaJIT site for specifics.
]]
print(ffi.string(ptr_my_thing.field_2))
Run Code Online (Sandbox Code Playgroud)
一种常见的误解是,诸如Lua和Python之类的通用语言不应该(或者,无知,不能)用于低级细节.LuaJIT是"智能"语言的主要第一步,允许您在任何级别工作.