我怎样才能将这个Python脚本最好地翻译成Lua?

时间:2014-06-29 05:50:55

标签: python lua translate

我试图将这个Python翻译成Lua,就像不熟悉Python的人一样。该功能取自http://rosettacode.org/wiki/Sierpinski_triangle#Python

def sierpinski(n):
    d = ["*"]
    for i in xrange(n):
        sp = " " * (2 ** i)
        d = [sp+x+sp for x in d] + [x+" "+x for x in d]
    return d

print "\n".join(sierpinski(4))

这是我到目前为止所做的,但它没有提供所需的输出。我在分析Python错了吗?我自己不认识Python,所以我认为情况就是这样。

function each(array,operation)
    --  Do an operation on each object in an array
    local out = {}
    for _,obj in pairs(array) do
        print(obj)
        table.insert(out,operation(obj))
    end
    return out
end

function join(...)
    --  Join two tables
    local out = {}
    for _,arr in pairs({...}) do
        for _,v in pairs(arr) do
            table.insert(out,v)
        end
    end
    return out
end

function sierpinski(n)
    local triangle = {"*"}
    for i = 1,n do
        local sp = (" "):rep(2^n)
        triangle = join(
            each(triangle,(function(x)
                return sp..x..sp
            end)),
            each(triangle,(function(x)
                return x.." "..x
            end))
        )
    end
    return table.concat(triangle,"\n")
end

print(sierpinski(4))

2 个答案:

答案 0 :(得分:3)

所以你的代码几乎是正确的:

    print(obj)

此行会产生不必要的打印,从而搞砸了一些东西。

for i = 1,n do

由于Python Lua之间的索引不同,因此应该是:0,n-1

    local sp = (" "):rep(2^n)

n应为i

所有这些都适用于我的机器:

function each(array,operation)
    --  Do an operation on each object in an array
    local out = {}
    for _,obj in pairs(array) do
        table.insert(out,operation(obj))
    end
    return out
end

function join(...)
    --  Join two tables
    local out = {}
    for _,arr in pairs({...}) do
        for _,v in pairs(arr) do
            table.insert(out,v)
        end
    end
    return out
end

function sierpinski(n)
    local triangle = {"*"}
    for i = 0,n-1 do
        local sp = (" "):rep(2^i)
        triangle = join(each(triangle,(function(x) return sp..x..sp end)), each(triangle,(function(x) return x.." "..x end)))
    end
    return table.concat(triangle,"\n")
end

答案 1 :(得分:2)

较短的版本:

local function sierpinski(n)
  local d = {'*'}
  for i = 0, n - 1 do
    local sp = string.rep(' ', 2^i)
    local len = #d
    for i = 1, len do
      local x = d[i]
      d[i] = sp .. x .. sp
      d[i+len] = x .. ' ' .. x
    end
  end
  return d
end

print(table.concat(sierpinski(4), '\n'))