Search code examples
c++lua

Saving the output from Lua in C++ with SOL3 to an std::string


I'm trying to implement a lua interpreter to my C++ code. I have implemented a small editor for my project using ImGui and I'm saving the output from the editor to an std::vector.

My attempted implementation of my lua interpeter looks like so;

// header
std::string ExecuteLua();
std::vector<char> m_luaEditorData;


// cpp
std::string Proxy::ExecuteLua()
{
    // Load the Lua code from the string
    std::string luaCode(m_luaEditorData.data());

    // Create a Lua state
    sol::state lua;

    // Load standard Lua libraries
    lua.open_libraries(sol::lib::base, sol::lib::package, sol::lib::string, sol::lib::table);

    // Execute the Lua code and store the result
    sol::protected_function_result result = lua.script(luaCode);

    // Check for errors
    if (!result.valid())
    {
        sol::error error = result;
        std::string errorMsg = error.what();
        return "Lua error: " + errorMsg;
    }

    // Get the result as a string
    std::string output = lua["tostring"](result.get<sol::object>());

    // Return the output
    return output;
}

...

        if (m_luaEditorData.empty())
            m_luaEditorData.push_back('\0');

            auto luaEditorFlags = ImGuiInputTextFlags_AllowTabInput | ImGuiInputTextFlags_CallbackResize;
            ImGui::InputTextMultiline("##LuaEditor", m_luaEditorData.data(), m_luaEditorData.size(), ImVec2(ImGui::GetWindowContentRegionWidth(), ImGui::GetWindowHeight() - (ImGui::GetTextLineHeight() * 16)), luaEditorFlags, ResizeInputTextCallback, &m_luaEditorData);

...

When I run this code, I only get nil in my output, the correct output to stdout (don't really want it to output here, but to my std::string and when I put in bad code, it throws an exception in sol.hpp. I didn't really find any examples on how I can do this and I'm therefore am trying to figure this out on my own.


Solution

  • I was able to solve the problem myself by replacing the print function with my own like so;

    int print(lua_State* L)
    {
        std::string printString = lua_tostring(L, 1);
        g_luaOutput += printString + "\n";
        return 1;
    }
    
    std::string Proxy::ExecuteLua()
    {
        std::string luaCode(m_luaEditorData.data());
    
        sol::state lua;
    
        lua.open_libraries(sol::lib::base, sol::lib::package, sol::lib::string, sol::lib::table, sol::lib::jit);
    
        lua.set_function("print", print);
    
        sol::protected_function_result result = lua.script(luaCode);
        ...
    

    When I now call print in my lua editor I will not print to my own console instead of stdout.