TI-Nspire & Lua / スクリプティングのヒント / メタテーブルを使う 7 / メタテーブルを直接使わずにクラスを利用する

Nspired Lua は class() ライブラリーが実装してあるのでメタテーブルを直接使わずにクラスが記述できる。

Class = class()
function Class:init(a, b)
   self[1] = a
   self[2] = b
end
function Class:setValue(where, what)
   rawset(self, where, what)
end


-- 確認してみる。
instTable_1 = Class(111, 222)
instTable_2 = Class("ABC", "DEF")
print("test_1: ", instTable_1[1], instTable_1[2], instTable_2[1], instTable_2[2])

instTable_1:setValue(1, 333)
print("test_2: ", instTable_1[1], instTable_1[2], instTable_2[1], instTable_2[2])

instTable_2:setValue(2, "GHI")
print("test_3: ", instTable_1[1], instTable_1[2], instTable_2[1], instTable_2[2])

instTable_2:setValue(-10000, "ZZZ")
print("test_4: ")
for k, v in pairs(instTable_1) do
   print(k, v)
end
for k, v in pairs(instTable_2) do
   print(k, v)
end

-- class() ライブラリーで作られるクラスももちろんテーブルである。
print("test_5:")
print(Class)
--print(type(Class))
for k, v in pairs(Class) do
   print(k, v)
end

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