Custom Types in LuaTables++ Done Right

October 22, 2013

Even though I am qute happy with LuaTables++ I figured storing and retrieval of custom types could be made even nicer. In my previous post I presented how one could add a custom type (i.e. a C++ struct or class) such that it can be assigned to values in Lua. It still required knowledge of the Lua C-API and would furthermore have made assignment of nested values more cumbersome. It now dawned to me that I could re-use facilities in LuaTables++ to circumvent both points.

For a struct of the form:

struct CustomType {
    string name;
    double age;
    bool drunken;
    double position[3];
};

especially setting the values of the double position[3] array would require creation of a new table which can be a bit cumbersome if one is not familiar with Lua’s stack. However this kind of functionality is already included in LuaTables++. Using the new API one can now implement the LuaTableNode::getDefault<CustomType>(const CustomType &value) function as:

template<>
CustomType LuaTableNode::getDefault<CustomType>(const CustomType &default_value) {
    CustomType result = default_value;

    if (exists()) {
        LuaTable custom_table = stackQueryTable();

        result.name = custom_table["name"].get<std::string>();
        result.age = custom_table["age"];
        result.drunken = custom_table["drunken"];
        result.position[0] = custom_table["position"][1];
        result.position[1] = custom_table["position"][2];
        result.position[2] = custom_table["position"][3];
    }

    stackRestore();

    return result;
}

and similarly the LuaTableNode::set<CustomType>(const CustomType &value) as:

template<>
void LuaTableNode::set<CustomType>(const CustomType &value) {
    LuaTable custom_table = stackCreateLuaTable();

    // set the fields of the custom type
    custom_table["name"] = value.name;
    custom_table["age"] = value.age;
    custom_table["drunken"] = value.drunken;
    custom_table["position"][1] = value.position[0];
    custom_table["position"][2] = value.position[1];
    custom_table["position"][3] = value.position[2];

    // restore the stack
    stackRestore();
}

One has to keep in mind that Lua starts its indices at 1 instead of 0. But apart from that I guess it should now be quite easy to add any kind of structs or classes even with complex member variables. If you have a suggestion to make it even simpler, let me know!