【问题标题】:How to iterate through luabind class (in lua or in c++)?如何遍历 luabind 类(在 lua 或 C++ 中)?
【发布时间】:2011-03-04 21:43:03
【问题描述】:

如何遍历 luabind 类(在 lua 或 c++ 中)?

class 'A'

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

谢谢

【问题讨论】:

    标签: c++ scripting lua luabind


    【解决方案1】:

    如果您要查找有关变量的反射信息(方法列表等),则可以使用 class_info()class_names() 函数。

    注意:据我所知,这些函数没有文档记录,但它们至少存在于 Luabind 0.9 中。使用风险自负。

    要在您的 Lua 代码中使用这些 Luabind 函数,您需要先绑定它们。示例:

    #include "luabind/class_info.hpp"
    /* ... */
    luabind::open(L);
    luabind::bind_class_info(L);
    

    然后从你的 Lua 代码中,你可以自省一个变量:

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

    您还可以获得 Luabind 知道的所有类的列表:

    for i, v in ipairs(class_names()) do print(v) end
    -- Prints:
    --   class_info_data
    --   Config
    --   Game
    --   ...
    

    【讨论】:

    • 谢谢。这是获取课程信息的非常有用的工具。我找了很久。但这并不能完全解决问题。这就是我在 luabind 邮件列表中找到的内容:“我想出了如何使用 class_info,它可以很好地检索类名和方法,但不检索属性。只有 c++ 公开的属性列在属性而不是属性下在 lua 中创建的。如何获得在 lua、c++ 中创建的属性列表及其值?"
    猜你喜欢
    • 2010-11-29
    • 2013-06-30
    • 2021-10-30
    • 2021-08-25
    • 2014-07-16
    • 2014-08-05
    • 2011-09-02
    • 1970-01-01
    相关资源
    最近更新 更多