lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Hello all,

I'm pretty new to Lua, and as it is an excellent piece of software, I now want to use it for scripting my C++ programs. I've read a good deal of the Programming in Lua book (okay, mostly Part 1 (The Language) and Part 4 (The C API)), and now I've a conceptual question.

For example, I want to create a scriptable GUI system. In C++, I'd write a class like

    class WindowT

        std::string      Name;
        unsigned long    BackgroundColor;
        WindowT*         Parent;
        ArrayT<WindowT*> Children;
        // ...
        // Many more attributes like position, size, border color...
        // ...

        virtual void OnDraw()
            // C++ code here to draw the window (and it's children)
            // to the screen.
            // ...

        virtual void OnActivatedEvent()
            // Run some Lua script here!

        // A lot more C++ related details follow here
        // that are not relevant for this example though.

In words, there is a hierarchy of windows, each of which has a name, a background color, a parent, children, etc. Given this, I want to have C++ code in OnDraw() to render each window to the screen (and possibly C++ code for several other methods), but I also want to execute Lua scripts e.g. as the event handlers.

For example, say we have a window "MainFrame" that has three children (sub-windows) with names "InfoText", "ButtonOK" and "ButtonCancel", then I would like to be able to have a Lua script that can e.g. modify the background color of the "MainFrame" window when the OnActivatedEvent() of the "ButtonCancel" subwindow is run.

My question is, how can I achieve this??

I've been thinking about implementing OnActivatedEvent() by first copying all C++ data of the entire window hierachy into a Lua table (identifying the individual windows by name, storing their data in sub-tables), then calling the associated Lua function, and finally copying back the entire window hierachy state from the Lua table to the C++ datastructures. This is of course a really bad and nonsense "solution". Another, much better approach is probably to add SetX() and GetX() methods for each attribute X of class WindowT, and then make these methods available to the Lua function that is called from OnActivatedEvent().

Nonetheless, I was still wondering how this is "normally" done, i.e. if maybe there is a much better solution to what looks like a common problem to me.

In order words, my question rephrased:
How can I have a complex C++ datastructure, and work with it *both* in C++ *and* in Lua code??

I'd be very grateful for any info. Thank you very much for your help!

Best regards,