Skip to content

Reflecting over substructs #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
MatthiasKauer opened this issue Jun 16, 2018 · 1 comment
Open

Reflecting over substructs #3

MatthiasKauer opened this issue Jun 16, 2018 · 1 comment

Comments

@MatthiasKauer
Copy link

Hi,
Let me first say that I'm quite excited about your reflection library and currently testing it out.
Concretely, I'm trying to iterate over the fields of substructs and it doesn't seem to work in the cases where I'd need it to. Maybe you have some advice. Here's what I am doing.

The following slightly shortened example from the docs works:

for refct in reflect.typeof[[
  struct {
    int a;
    union { int b; int c; };
    struct { int e; int f; };
  }
]]:members() do print(refct.what) end --> field, union, struct

Naming the outer struct has the fields of the inner struct inlined(?) but they can still be iterated.

-- from https://github.com/corsix/ffi-reflect/blob/master/test.lua
local function rec_members(refct, f)
  if refct.members then
    for refct in refct:members() do
      rec_members(refct, f)
    end
  else
    f(refct)
  end
end

ffi.cdef [[
  struct Test1 {
    int a;
    union { int b; int c; };
    struct { int e; int f; };
  };
]]
rec_members(reflect.typeof("struct Test1"), function(rc) print(rc.what) print(rc.name) end)
--> field a field b field c field e field f

If I name the inner struct, I cannot access its fields at all.

ffi.cdef [[
  struct Inner { int e; int f; };
  struct Test2 {
    int a;
    union { int b; int c; };
    struct Inner inner;
  };
]]
rec_members(reflect.typeof("struct Test2"), function(rc) print(rc.what) print(rc.name) end)
--> field a field b field c field inner

Is there another way to make this work? Any chance that getting this only requires a small change?

@sonoro1234
Copy link

can work with this rec_members

local function rec_members(refct, f)
  if refct.members then
    for refct in refct:members() do
      rec_members(refct, f)
    end
  elseif refct.type and refct.type.members then
      rec_members(refct.type, f)
  else
    f(refct)
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants