2016年1月29日金曜日

開発環境

  • OS X El Capitan - Apple (OS)
  • Emacs (Text Editor)
  • Lua (プログラミング言語)

Seven More Languages in Seven Weeks (Bruce Tate (著)、Ian Dees (著)、Frederic Daoud (著)、Jack Moffitt (著)、Pragmatic Bookshelf)のChapter 1(Lua)、Day 2(Tables All the Way Down)、Do (Medium)(No. 1199).を取り組んでみる。

Do (Medium)(No. 1199)

コード(Emacs)

function concatenate(a1, a2)
   local result = a1
   for k, v in pairs(a2) do
      result[#result + 1] = v
   end
   return result
end


a1 = {'a', 'b', 'c', 'd', 'e'}
a2 = {'f', 'g', 'h', 'i', 'j'}

local mt = {
   __add = concatenate
}

setmetatable(a1, mt)
setmetatable(a2, mt)
a = a1 + a2

for k, v in pairs(a) do
   print(v)
end

Queue = {
   first = 1,
   last = 1,
   obj = {},
   new = function (self)
      local obj = self.obj
      setmetatable(obj, self)
       self.__index = self
      return obj
   end,
   add = function (self, item)
      self.obj[self.last] = item
      self.last = self.last + 1
   end,
   remove = function(self)
      if self.first < self.last then
         self.first = self.first + 1
         return self.obj[self.first - 1]         
      else
         return nil
      end      
   end,
   print = function(self)
      print("Queue----------")
      local i = self.first
      while i < self.last do
         print(self.obj[i])
         i = i + 1
      end
   end   
}

q = Queue.new(Queue)
q.print(q)
q.add(q, 'item1')
q.print(q)
q.add(q, 'item2')
q.print(q)
q.remove(q)
q.print(q)
q.remove(q)
q.print(q)
q.remove(q)
q.print(q)

入出力結果(Terminal)

$ lua sample_medium.lua
a
b
c
d
e
f
g
h
i
j
Queue----------
Queue----------
item1
Queue----------
item1
item2
Queue----------
item2
Queue----------
Queue----------
$

0 コメント:

コメントを投稿

Comments on Google+: