Re: Possible to store a reference to a lua table in an ffi struct?

  • From: Evan Wies <evan@xxxxxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Sun, 23 Mar 2014 08:27:54 -0400

On 3/22/14, 8:22 PM, Kaj Eijlers wrote:

    Using that same technique, you can store just the
    vector<string>-replacement table in the metatable.  The downside
    of this approach is that you will need a different
    metatype/metatable for each instance (unless the intention is to
    share this vector<string> among among instances, i.e. a C++ static
    class member).

    For example:
    t = ffi.metatype( "struct { int a, b, c; }", { __index = { vstr =
    {} } })
    foo = t()
    foo.vstr[#foo.vstr+1] = "string1"

    -Evan

Hmmmmm, No I need a vector per instance, so I think I'll go with a member that is a ctype with a metatable for push_back() and the likes. But thanks for the idea, I'll keep it in mind :o)
You can have a vector per instance. But it needs to be created with a new metatype each time and ffi.metatype is not JIT compiled (but maybe not such a big deal with 2.1 and trace stitching).

local struct_t = ffi.typeof("struct { int a, b, c; }")  -- make one ctype
local function new_instance()
    -- but have many metatatypes
    return ffi.metatype( struct_t, { __index = {
        vstr = setmetatable( {}, {
            __index = { push_back = function(t, s) t[#t+1] = s end }
        })
    }})
end

f = new_instance()
f.vstr:push_back("f")
g = new_instance()
g.vstr:push_back("g")

-Evan

Other related posts: