クラスを使う 3, 複数のオブジェクトを tab キーで巡廻する
-- 複数のオブジェクトを tab キーで巡廻する。 -- 参考: http://compasstech.com.au/TNS_Authoring/Scripting/script_tut14.html require "color" TrackedObject = nil Square = class() function Square:init(x, y, sideLen, color) self.x = x self.y = y self.sideLen = sideLen self.color = color self.selected = false end function Square:contains(x, y) return self.x <= x and x <= self.x + self.sideLen and self.y <= y and y <= self.y + self.sideLen end function Square:paint(gc) gc:setColorRGB(self.color) gc:fillRect(self.x, self.y, self.sideLen, self.sideLen, self.color) if self.selected then gc:setColorRGB(color.black) gc:setPen("thick") gc:drawRect(self.x, self.y, self.sideLen, self.sideLen) end end Objects = { Square(10, 80, 50, 0xD90000), Square(70, 80, 50, 0xD94000), Square(130, 80, 50, 0xD98000), Square(190, 80, 50, 0xD9C000), Square(250, 80, 50, 0xD9FF00) } function on.tabKey() if TrackedObject then --1. すでに「注目オブジェクト」に何か入っていたら、 TrackedObject.selected = false --2. その選択状態を解除する。「注目オブジェクト」が空であった場合は元々何も選択されていないということなので何もしない。 end for i = 1, #Objects do --3. オブジェクトリストを左から順に走査して、 if Objects[i] == TrackedObject then --4. 旧「注目オブジェクト」に一致する要素が見つかったら、 TrackedObject = Objects[i+1] --5. ひとつ右の要素を新「注目オブジェクト」にセットして、 break --6. ループを抜ける。 end end if TrackedObject == nil then --7. 「注目オブジェクト」が空であったら、 TrackedObject = Objects[1] --8. 先頭の要素を新「注目オブジェクト」にセットする。 end TrackedObject.selected = true --9. 最後に新「注目オブジェクト」を選択状態に変える。 platform.window:invalidate() end function on.backtabKey() -- on.tabKey() と逆の動きにする。 if TrackedObject then TrackedObject.selected = false end for i = #Objects, 1, -1 do if Objects[i] == TrackedObject then TrackedObject = Objects[i-1] break end end if TrackedObject == nil then TrackedObject = Objects[#Objects] end TrackedObject.selected = true platform.window:invalidate() end function on.escapeKey() if TrackedObject then TrackedObject.selected = false end TrackedObject = nil platform.window:invalidate() end function on.paint(gc) for i = 1, #Objects do Objects[i]:paint(gc) end end