Rosetta Code (Lua)

I ran across the very-awesome Rosetta Code again recently, and only for the first time appreciated how I might use it as a source of programming projects. I've always been attracted to small languages that use a few primitives in many ways. Lua has a small runtime and featues tables as its sole data structure. Lua has quite a few tasks left to implement, so I just scrolled through the list to find some interesting tasks.

Sierpinski Triangle

<2019-09-22 Sun>

It turns out I thought Sierpinski Triangle sounded interesting.

I've been familiar with the Sierpinski Triangle as a self-similar shape, and have programmed them before using Logo-like languages, which turn drawing problems into driving problems. I'd certainly never approached it from the perspective of printing it to the terminal as a string.

My initial thought was to write a function to draw a triangle of depth 2, and then use that function to stamp out copies into a character array that I'd then blit to the screen before exiting. This approach turned out to be much more difficult than I expected: I was able to make some headway drawing the right edge this way, but soon found myself tackling both the problem and the language. As a newcomer to Lua, I thought it might be better to revisit my own implementation after I learned more with Lua, so I took a step back.

I instead proceeded by reading a solution to the problem in other languages that I knew. In particular, the solution using list-comprehensions in Python was short and easy to follow, so I decided to replicate it in Lua.

function sierpinski(depth)
   lines = {}
   lines[1] = '*'

   for i = 2, depth+1 do
      sp = string.rep(' ', 2^(i-2))
      tmp = {}
      for idx, line in ipairs(lines) do
         tmp[idx] = sp .. line .. sp
         tmp[idx+#lines] = line .. ' ' .. line
      end
      lines = tmp
   end
   return table.concat(lines, '\n')
end

print(sierpinski(4))

This worked pretty well, since I only focused on reimplementing an existing algorithm in a new language, rather than trying to learn the language and develop an algorithm at the same time.

back