【问题标题】:Code conversion from Python to Lua almost completed从 Python 到 Lua 的代码转换几乎完成
【发布时间】:2019-02-26 04:52:10
【问题描述】:

我找到了一个我正在尝试转换为 Lua 的 Python 脚本。我相信我刚刚转换了它,但是代码不能正常工作,所以我需要帮助,因为我根本不了解 Python,只能猜测意图。这只是一个将 RGB 颜色转换为 xterm 256 的颜色转换器。表格非常大,因此我将其截断以方便阅读。

Python 代码:

import sys, re

CLUT = [  # color look-up table
#    8-bit, RGB hex

    # Primary 3-bit (8 colors). Unique representation!
    ('00',  '000000'),
    ('01',  '800000'),
    ('02',  '008000'),
    ('03',  '808000'),
    ('04',  '000080'),
    ('05',  '800080'),
    ('06',  '008080'),
    ('07',  'c0c0c0'),
]

def _str2hex(hexstr):
    return int(hexstr, 16)

def _strip_hash(rgb):
    # Strip leading `#` if exists.
    if rgb.startswith('#'):
        rgb = rgb.lstrip('#')
    return rgb

def _create_dicts():
    short2rgb_dict = dict(CLUT)
    rgb2short_dict = {}
    for k, v in short2rgb_dict.items():
        rgb2short_dict[v] = k
    return rgb2short_dict, short2rgb_dict

def short2rgb(short):
    return SHORT2RGB_DICT[short]

def print_all():
    """ Print all 256 xterm color codes.
    """
    for short, rgb in CLUT:
        sys.stdout.write('\033[48;5;%sm%s:%s' % (short, short, rgb))
        sys.stdout.write("\033[0m  ")
        sys.stdout.write('\033[38;5;%sm%s:%s' % (short, short, rgb))
        sys.stdout.write("\033[0m\n")
    print "Printed all codes."
    print "You can translate a hex or 0-255 code by providing an argument."

def rgb2short(rgb):
    """ Find the closest xterm-256 approximation to the given RGB value.
    @param rgb: Hex code representing an RGB value, eg, 'abcdef'
    @returns: String between 0 and 255, compatible with xterm.
    >>> rgb2short('123456')
    ('23', '005f5f')
    >>> rgb2short('ffffff')
    ('231', 'ffffff')
    >>> rgb2short('0DADD6') # vimeo logo
    ('38', '00afd7')
    """
    rgb = _strip_hash(rgb)
    incs = (0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff)
    # Break 6-char RGB code into 3 integer vals.
    parts = [ int(h, 16) for h in re.split(r'(..)(..)(..)', rgb)[1:4] ]
    res = []
    for part in parts:
        i = 0
        while i < len(incs)-1:
            s, b = incs[i], incs[i+1]  # smaller, bigger
            if s <= part <= b:
                s1 = abs(s - part)
                b1 = abs(b - part)
                if s1 < b1: closest = s
                else: closest = b
                res.append(closest)
                break
            i += 1
    #print '***', res
    res = ''.join([ ('%02.x' % i) for i in res ])
    equiv = RGB2SHORT_DICT[ res ]
    #print '***', res, equiv
    return equiv, res

RGB2SHORT_DICT, SHORT2RGB_DICT = _create_dicts()

#---------------------------------------------------------------------

if __name__ == '__main__':
    import doctest
    doctest.testmod()
    if len(sys.argv) == 1:
        print_all()
        raise SystemExit
    arg = sys.argv[1]
    if len(arg) < 4 and int(arg) < 256:
        rgb = short2rgb(arg)
        sys.stdout.write('xterm color \033[38;5;%sm%s\033[0m -> RGB exact \033[38;5;%sm%s\033[0m' % (arg, arg, arg, rgb))
        sys.stdout.write("\033[0m\n")
    else:
        short, rgb = rgb2short(arg)
        sys.stdout.write('RGB %s -> xterm color approx \033[38;5;%sm%s (%s)' % (arg, short, short, rgb))
        sys.stdout.write("\033[0m\n")

还有我几乎完整翻译的 Lua 代码:

CLUT = {
    -- Primary 3-bit (8 colors). Unique representation!
    ['00'] = '000000',
    ['01'] = '800000',
    ['02'] = '008000',
    ['03'] = '808000',
    ['04'] = '000080',
    ['05'] = '800080',
    ['06'] = '008080',
    ['07'] = 'c0c0c0',
}

function _str2hex(hexstr)
    return tonumber(hexstr, 16)
end

function _strip_hash(rgb)
    -- Strip leading # if exists
    return rgb:gsub("^#", "")
end

function _create_dicts()
    short2rgb_dict = CLUT
    rgb2short_dict = {}

    for k,v in pairs(short2rgb_dict) do
        rgb2short_dict[v] = k
    end
    return rgb2short_dict, short2rgb_dict
end

function short2rgb(short)
    return short2rgb_dict[short]
end

function rgb2short(rgb)
    -- Find closest xterm-256 approximation to the given RGB value
    _create_dicts()
    rgb = _strip_hash(rgb)
    local res = ""
    local equiv = ""

    local incs = {"0x00", "0x5f", "0x87", "0xaf", "0xd7", "0xff"}

    for part in string.gmatch(rgb, "(..)") do
        part = tonumber(part, 16)
        i = 1
        while i < #incs - 1 do
            s, b = tonumber(incs[i]), tonumber(incs[i+1])
            if s <= part and part <= b then
                s1 = math.abs(s - part)
                b1 = math.abs(b - part)
            end

            if s1 < b1 then
               closest = s
            else
                closest = b
                res = res .. closest
                break
            end
            i = i + 1
        end
    end

    equiv = rgb2short_dict[res]

    return equiv, res
end

我意识到我错过了代码的打印部分,但我不确定这是否相关,而且我知道我翻译的一些代码根本不正确,因为脚本否则会工作。我遇到的失败是 rgb2short 函数没有返回正确的 equivres 值。我离修订还有多远?我需要进行哪些更改才能使其完全正常工作?

【问题讨论】:

    标签: python lua code-translation


    【解决方案1】:

    经过一些顽固的反复试验,我最终自己解决了这个问题。函数rgb2short 应该是:

     function rgb2short(rgb)
         -- Find closest xterm-256 approximation to the given RGB value
         _create_dicts()
         rgb = _strip_hash(rgb)
         local res = ""
         local equiv = ""
    
         local incs = {"0x00", "0x5f", "0x87", "0xaf", "0xd7", "0xff"}
    
         for part in string.gmatch(rgb, "(..)") do
             part = tonumber(part, 16)
             i = 1
             while i < #incs-1 do
                 s, b = tonumber(incs[i]), tonumber(incs[i+1])
                 if s <= part and part <= b then
                     s1 = math.abs(s - part)
                     b1 = math.abs(b - part)
                     --break
                 --end
    
                     if s1 < b1 then
                         closest = s
                     else
                         closest = b
                     end
                     res = res .. string.format("%02x", closest)
                     break
                 end
                 i = i + 1
             end
         end
    
    
         equiv = rgb2short_dict[res]
    
         return equiv, res
     end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-10
      • 1970-01-01
      • 2011-04-18
      • 1970-01-01
      • 2011-04-20
      • 2019-06-21
      • 1970-01-01
      相关资源
      最近更新 更多