2016年1月28日木曜日

開発環境

  • 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 (Easy)(No. 1191).を取り組んでみる。

Do (Easy)(No. 1191)

コード(Emacs)

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

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

i = 1
while i <= 10 do
   print(a[i])
   i = i + 1
end

local _private = {}

function strict_read(table, key)
   if _private[key] then
      return _private[key]
   else
      error("Invalid key: " .. key)
   end
end

function strict_write(table, key, value)
   if _private[key] and not (value == nil) then
      error("Duplicate key: " .. key)
   else
      _private[key] = value
   end
end

local mt = {
   __index = strict_read,
   __newindex = strict_write
}
treasure = {}
setmetatable(treasure, mt)

入出力結果(Terminal)

$ lua -l sample_easy
f
g
h
i
j
a
b
c
d
e
Lua 5.3.1  Copyright (C) 1994-2015 Lua.org, PUC-Rio
> treasure.gold = 50
> treasure.gold
50
> treasure.silver
./sample_easy.lua:26: Invalid key: silver
stack traceback:
 [C]: in function 'error'
 ./sample_easy.lua:26: in function 'strict_read'
 stdin:1: in main chunk
 [C]: in ?
> treasure.gold = 100
./sample_easy.lua:32: Duplicate key: gold
stack traceback:
 [C]: in function 'error'
 ./sample_easy.lua:32: in function 'strict_write'
 stdin:1: in main chunk
 [C]: in ?
> treasure.gold
50
> treasure.gold = nil
> treasure.gold
./sample_easy.lua:26: Invalid key: gold
stack traceback:
 [C]: in function 'error'
 ./sample_easy.lua:26: in function 'strict_read'
 stdin:1: in main chunk
 [C]: in ?
> treasure.gold = 100
> treasure.gold
v100
>
$

0 コメント:

コメントを投稿

Comments on Google+: