-3

I have this function in Lua:

Len = function(msg, length, dir)
    if not msg or not length then
        return "Unknown";
    end
    local msgC = msg:gsub("$%d", "");
    if (dir == "l") then
        return string.rep(" ", length - #msgC)..msg;
    else
        return msg..string.rep(" ", length - #msgC);
    end
end

It pads a string in the specified direction, resulting in a string that is either right-aligned or left-aligned to the number of characters specified (primarily used for formatting lists).

I tried to replicate the above function in C++:

std::string Len(string msg, int charCount, string dir) 
{
    int spacesRequired = (charCount-msg.length()/2);
    std::ostringstream pStream;
    if (dir == "l")
        pStream << std::string(spacesRequired, ' ') << msg;
    else
        pStream << msg << std::string(spacesRequired, ' ');
    return pStream.str();
}

...which doesn't work properly:

enter image description here

I also use a function to centre the whole string before it is printed, but that's irrelevant here since the issue is with the Len C++ function.

What did I do wrong here, and how can I correct this?

I'm thinking the problem is my misunderstanding of local msgC = msg:gsub("$%d", ""); which (to my understanding, which may be incorrect) retrieves the length of the string. This resulted in int spacesRequired = (charCount-msg.length()/2); which does the same as length - #msgC.

AStopher
  • 4,207
  • 11
  • 50
  • 75

1 Answers1

0

I failed to take into account the colour codes.

The game uses colour codes with $[0-9] in order to provide the ability to colour console messages for the game. It appears what msg:gsub("$%d", "") does is that it searches for these colour codes and returns the amount present; my C++ function did not do this.

All I had to do is modify the function in order to search for these colour codes and add them to charCount. To do this I used part of the code in How can I ignore certain strings in my string centring function?:

std::string Aurora64::Length(string msg, int charCount, string dir) 
{
    int msgC = 0;
    std::string::size_type pos = 0;
    while ((pos = msg.find('$', pos)) != std::string::npos) {
        if (pos + 1 == msg.size()) {
            break;
        }
        if (std::isdigit(msg[pos + 1])) {
            msgC++;
        }
        ++pos;
    }
    charCount=charCount+msgC;

    int spacesRequired = charCount-(msg.length()-msgC);
    std::ostringstream pStream;
    if (dir == "l")
        pStream << std::string(spacesRequired, ' ') << msg;
    else
        pStream << msg << std::string(spacesRequired, ' ');
    return pStream.str();
}

...which now results in the desired output:

enter image description here

The small fluke in the third message was caused by an extra space in the message itself, so not a problem.

Community
  • 1
  • 1
AStopher
  • 4,207
  • 11
  • 50
  • 75