【问题标题】:How can I properly copy the functionality of this Lua function? [duplicate]如何正确复制此 Lua 函数的功能? [复制]
【发布时间】:2016-11-07 16:37:17
【问题描述】:

我在 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

它在指定方向填充一个字符串,从而产生一个与指定字符数右对齐或左对齐的字符串(主要用于格式化列表)。

我尝试在 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();
}

...不能正常工作:

我还使用一个函数在打印整个字符串之前使其居中,但这在这里无关紧要,因为问题在于 Len C++ 函数。

我在这里做错了什么,我该如何纠正?

我认为问题在于我对 local msgC = msg:gsub("$%d", ""); 的误解(据我了解,这可能是不正确的)检索字符串的长度。这导致int spacesRequired = (charCount-msg.length()/2);length - #msgC 的作用相同。

【问题讨论】:

    标签: c++ lua


    【解决方案1】:

    我没有考虑颜色代码。

    游戏使用带有$[0-9] 的颜色代码,以便为游戏提供着色控制台消息的能力。看来msg:gsub("$%d", "") 所做的是搜索这些颜色代码并返回存在的数量;我的 C++ 函数没有这样做。

    我所要做的就是修改函数以搜索这些颜色代码并将它们添加charCount。为此,我使用了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();
    }
    

    ...现在会产生所需的输出:

    第三条消息中的小侥幸是由消息本身的多余空格引起的,所以不是问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      • 2017-09-07
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多