It's a function that takes a table and returns a struct with matching boolean and numeric fields, with __index pointing back to the table. It might be useful in some cases where table access happens frequently but table creation happens infrequently, for tables containing mostly numbers and booleans (like vectors).
It might also be a good jumping off point for something more elaborate. For example it might be nice to reuse struct declarations for tables with matching "signatures," arrange the struct's fields in a more predictable way, add special handling for strings, etc..
Code: Select all
--struct.lua
local ffi = require 'ffi'
local typemap = { boolean = 'bool', number = 'double' }
local function struct (t)
local fields = {}
local init = {}
for key, value in pairs(t) do
local typename = typemap[type(value)]
if typename then
init[key] = value
fields[#fields + 1] = ('%s %s; '):format(typename, key)
end
end
local cdecl = ('struct { %s}'):format(table.concat(fields))
return ffi.metatype(cdecl, { __index = t })(init)
end
return struct