まとめ:セキュアな保管庫
CoddyのLuaジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 48/70。
チャレンジ
簡単Vault クラスを構築し、closure-based privacy を使用して本当に secure なストレージシステムを作りましょう!vault には、correct な password を提供した場合にのみ access できる秘密の contents が保存されます。
コードを2つのファイルに分けて整理します。
Vault.lua: contents と password の両方を Constructor 内の local 変数に保存するクラスを作成します。外部からの access から完全に隠蔽されます。Constructor:new(contents, password)はこれらの値を local 変数に保存し、その後、method を object instance に直接定義します。:open(attemptedPassword): attempted password が保存された password と matches するかを確認します。correct なら秘密の contents を返し、incorrect なら"Access Denied"を返します。
main.lua: Vault module を Require し、3つの inputs を読み取ります。保存する秘密の contents、設定する password、そして password attempt です。contents と password を使って vault を Create し、attempted password で vault を open して Result を Print します。また、vault.contentsに直接 access して得られるものを Print することで、contents が本当に private であることも示します。
3つの inputs が与えられます。
- vault に保存する秘密の contents
- vault を保護する password
- vault を open するための password attempt
出力は次の2行になります。
Result: {resultFromOpen}
Direct access: {whatYouGetFromVaultContents}たとえば、inputs が Gold Coins、secret123、secret123 の場合、出力は次のようになります。
Result: Gold Coins
Direct access: nilinputs が Diamond、mypass、wrongpass の場合、出力は次のようになります。
Result: Access Denied
Direct access: nilここでの key insight は、contents と password の両方が Constructor 内の local 変数としてのみ存在することです。:open() method は closure を通じてそれらに access できますが、それ以外のものは access できません。vault.contents、vault._contents、vault.password でさえ access できません。これが真の encapsulation です!
自分で試してみよう
-- Vaultモジュールを読み込む
local Vault = require('Vault')
-- 入力を読み取る
local contents = io.read()
local password = io.read()
local attemptedPassword = io.read()
-- TODO: contentsとpasswordでvaultを作成する
-- TODO: attempted passwordでvaultを開いてみる
-- TODO: 結果を次の形式で出力する: "Result: {resultFromOpen}"
-- TODO: vault.contentsに直接アクセスして、得られるものを出力する
-- Print in the format: "Direct access: {whatYouGetFromVaultContents}"
オブジェクト指向プログラミングのすべてのレッスン
自分で練習してみよう: Luaオンラインコンパイラ