Generic table to FFI struct demo

Showcase your libraries, tools and other projects that help your fellow love users.
Post Reply
User avatar
airstruck
Party member
Posts: 650
Joined: Thu Jun 04, 2015 7:11 pm
Location: Not being time thief.

Generic table to FFI struct demo

Post by airstruck »

Here's something I was playing with to get more familiar with LuaJIT's FFI. I got the idea from this post.

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
If you think this could improve performance with some of your existing code, please give it a shot and let me know how it goes.
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot] and 59 guests