Modules exampleΒΆ

/**
 * This example demonstrates how to create reusable modules and embed them to scripts
 */

int main()
{
    rlogic::LogicEngine logicEngine;

    // Create a module which wraps Lua's print method and prints the name of the caller
    rlogic::LuaModule* myPrint = logicEngine.createLuaModule(R"(
        local myPrint = {}

        function myPrint.print(name)
            print("Hello, " .. name .. "!")
        end

        return myPrint
    )");

    // Create a LuaConfig object which we use to configure how the module
    // shall be mapped to the script later (under the alias 'PrintModule')
    rlogic::LuaConfig modulesConfig;
    modulesConfig.addDependency("PrintModule", *myPrint);

    // Create a script which uses the custom print module. Notice that the script
    // declares its dependency to a PrintModule via the modules() function
    rlogic::LuaScript* script = logicEngine.createLuaScript(R"(
        -- The script must declare the modules it depends on
        -- The name here must match the alias provided in the LuaConfig above!
        modules('PrintModule')

        function interface()
            IN.name = STRING
        end

        function run()
            -- Calls the 'print' function packaged in the PrintModule
            PrintModule.print(IN.name)
        end
    )", modulesConfig, "ScriptWithModule");

    // Set the name input
    script->getInputs()->getChild("name")->set<std::string>("MrAnderson");

    // Update the logic engine (will print 'Hello MrAnderson')
    logicEngine.update();

    // Modules have to be destroyed after all scripts that reference them have been destroyed
    logicEngine.destroy(*script);
    logicEngine.destroy(*myPrint);