Time for action – Loading scripts provided by users

Each player will provide their own strategy script, so the Scene class should have a field for storing all provided scripts:

QHash<int, QJSValue> m_teamScripts;

Let's provide the setScript() function that accepts the player's script and loads it into the JS engine:

void Scene::setScript(int team, const QString &script) {
    QJSValue value = m_jsEngine.evaluate(script);
    if (value.isError()) {
        qDebug() << "js error: " << value.toString();
        return;
    }
    if(!value.isObject()) {
        qDebug() << "script must return an object";
        return;
    }
    m_teamScripts[team] = value;
}

In this function, we try to evaluate the provided code. If the code returned a JavaScript object, we put it in the m_teamScripts hash table. ...

Get Game Programming using Qt 5 Beginner's Guide - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.