Take the 2-minute tour ×

How to iterate through luabind class (in lua or in c++)?

class 'A'

function A:__init()
    -- Does not work
    -- self is userdata, not a table
    for i, v in pairs(self) do


share|improve this question

2 Answers 2

If you're trying to look up reflection information about a variable (list of methods, etc.) then you can use the class_info() and class_names() functions.

Note: These functions aren't documented as far as I can tell, but they at least exist in Luabind 0.9. Use at your own risk.

To use these Luabind functions in your Lua code, you need to bind them first. Example:

#include "luabind/class_info.hpp"
/* ... */

Then from your Lua code, you can introspect a variable:

-- Variable "game" is an instance of class "Game"
c = class_info(game)

-- Prints:
--   Game

for k, v in pairs(c.methods) do print(k, v) end
-- Prints:
--   get_config    function: 01765AE0
--   on_init       function: 01765E90
--   ...

for k, v in pairs(c.attributes) do print(k, v) end
-- ...

You can also get a list of all the classes Luabind knows about:

for i, v in ipairs(class_names()) do print(v) end
-- Prints:
--   class_info_data
--   Config
--   Game
--   ...
share|improve this answer
Thanks. It is a very helpful tool to get a class info. I was looking for it for a long time. But it doesn't fully solves the problem. That's what I've found in luabind mailing list: "I figured out how to use class_info and it works great to retrieve the class name and methods but not the attributes. Only the attributes that are exposed by c++ are listed under Attributes not the attributes that are created in lua. How would I get a list of attributes created in lua, in c++ and their value?" –  kFk Jun 18 '10 at 8:26

I'm just guessing here, but luabind probably uses the __index and __newindex metamethods for class members. You may be able to iterate over the __index member of the metatable for class A, unless it is bound to a function instead of a table.

I'll take a look at luabind later and make an update to this answer. Normally, I just roll my own bindings.

share|improve this answer
Did you found the answer? Thanks in advance. –  kFk Jun 21 '10 at 9:07

Your Answer


