TI-Nspire & Lua / スクリプティングのヒント / メタテーブルを使う 8 / スタックを実装する

参考: お気楽 Lua プログラミング超入門

Stack = class()
function Stack:init(size)
   self.buff = {}
   self.size = size or math.huge
end
function Stack:push(val)
   if #self.buff < self.size then
      table.insert(self.buff, val)
   else
      error("Error: Stack is full.", 0) -- 上限を超えて push したときにエラーを出す。 
   end
end
function Stack:pop()
   if #self.buff > 0 then
      return table.remove(self.buff)
   else
      error("Error: Stack is empty.", 0) -- 空のスタックから pop したときにエラーを出す。
   end
end


-- 確かめてみる。
stack = Stack(10)
for i = 1, 5 do -- 1 から順番に push する。
   stack:push(i)
   print(i)
end
while true do -- 最後に push した値から順番に pop する。
   print(stack:pop())
end

f:id:ti-nspire:20170217081215p:plain
 

-- 確かめてみる。
stack = Stack(5)
for i = 1, 999 do -- 1 から順番に push する。
   stack:push(i)
   print(i)
end

f:id:ti-nspire:20170217080541p:plain