초등학교 때 배우는 두 정수의 곱셈표를 만들어 주는 Lua 소스이다.

--[[
  Filename: makeMultTable.lua

      Print a multiplication table.

      Execute: lua makeMultTable.lua 230 5100

  Date: 2009/03/06
--]]

function printUsing()
    print("Using: lua makeMultTable.lua [number1] [number2]")
    print("Print a multiplication table for the given two integers.")
end

function printMultTable(x, y)
    nx = x
    if nx < 0 then
        nx = -nx
    end
    ny = y
    if ny < 0 then
        ny = -ny
    end
    ntail1 = 0
    ntail2 = 0
    while nx % 10 == 0 do
        nx = nx / 10
        ntail1 = ntail1 + 1
    end
    while ny % 10 == 0 do
        ny = ny / 10
        ntail2 = ntail2 + 1
    end
    z = nx * ny
    strZ = "" .. z
    strX = "" .. nx
    strY = "" .. ny
    n = string.len(strY)
    zeros  = "0000000000000000000000000000000000000000"
    whites = "                                        "
    bars   = "----------------------------------------"
    loffset = "       "
    line4 = loffset .. strZ
    line1 = loffset .. string.sub(whites, 1, string.len(strZ) - string.len(strX)) .. strX
    line2 = "   x ) " ..  string.sub(whites, 1, string.len(strZ) - string.len(strY)) .. strY
    line3 = "     --" ..  string.sub(bars, 1, string.len(strZ))
    print(line1 .. string.sub(zeros, 1, ntail1))
    print(line2 .. string.sub(zeros, 1, ntail2))
    print(line3)
    if string.len(strY) > 1 then
        for i = 1, string.len(strY) do
            y1 = tonumber(string.sub(strY, string.len(strY) - i + 1, string.len(strY) - i + 1))
            if y1 ~= 0 then
                strT = "" .. (nx * y1)
                print(loffset .. string.sub(whites, 1, string.len(strZ) - string.len(strT) - i + 1) .. strT)
            end
        end
        print(line3)
    end
    print(line4 .. string.sub(zeros, 1, ntail1) ..  string.sub(zeros, 1, ntail2))
end

if #arg >= 2 then
    x = tonumber(arg[1])
    y = tonumber(arg[2])
    print()
    printMultTable(x, y)
else
    printUsing()
end



실행> lua makeMultTable.lua 230 5100
결과>

          230
   x )   5100
     ------
         23
       115
     ------
       1173000

 

크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,