Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
    end
end

Thanks

like image 261
kFk Avatar asked Jun 17 '10 10:06

kFk


1 Answers

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"
/* ... */
luabind::open(L);
luabind::bind_class_info(L);

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

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

print(c.name)
-- 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
--   ...
like image 162
ZoogieZork Avatar answered Oct 02 '22 14:10

ZoogieZork