How can one implement OO in Lua?

后端 未结 5 1956
自闭症患者
自闭症患者 2021-02-01 06:04

Lua does not have build in support for OO, but it allows you to build it yourself. Could you please share some of the ways one can implement OO?

Please write one example

5条回答
  •  無奈伤痛
    2021-02-01 06:49

    The best solution I saw is not to implement OO in Lua, where it is not natural and patchy, and hence takes many lines; rather, implement it in C++ using luabridge or luabind, where it is natural and powerful!

    A minimalistic example which uses LuaBridge:

    m.class_("MyClass")
    .constructor()
    .method("method1", &MyClass::method1)
    .property_rw("property2", &MyClass::getter2, &MyClass::setter2)
    .property_ro("property3", &MyClass::property3)
    

    This would translate into natural lua syntax:

    c=MyClass()
    c.method1()
    c.property2 = c.property3 * 2
    do_stuff(c.property3)
    

    Also one-level inheritence is supported...

提交回复
热议问题