Luaレッスン「オブジェクト・クラス」(番外編)

--

http://inspired-lua.org/index.php/2011/05/5-object-classes/

 に紹介されているスクリプトを実行してみた

Shape = class() --Shapeクラスを作成
function Shape:init(x, y, image) -- 初期化。(左上角の座標, 画像ハンドル)。
     self.xpos = x
     self.ypos = y
     self.pic = image
end

xmin = 20 --xyの範囲を指定
ymin = 20
xmax = 150
ymax = 150

smiley = image.new(_R.IMG.smiley) --画像を読み込む
red_square = image.new(_R.IMG.red_square)
shape1 = Shape(xmin + 20, ymin + 20, smiley)
shape2 = Shape(xmax - 10, ymax - 10, red_square)

function Shape:paint(gc) --Shapeクラスの描画函数を作成
     gc:drawImage(self.pic, self.xpos, self.ypos) --(画像ハンドル、左上角の座標)
end

function Shape:setxy(newx, newy) --Shapeクラスのxy座標を新しい値(newx, newy)に設定する函数を作成
     if newx > xmin and --(newx, newy)が(xmin, ymin)~(xmax, ymax)の範囲内にある場合は
     newx < xmax and
     newy > ymin and
     newy < ymax then
          self.xpos = newx --新しい座標を自身の座標にする
          self.ypos = newy
     end
end
function Shape:move(dx, dy) --Shapeクラスを(dx, dy)のぶんだけ動かす函数を作成
     local newx, newy
     self:setxy(self.xpos + dx,self.ypos + dy) --現在の座標から(dx, dy)のぶんだけ動かした座標を自身の座標とする
end

function on.paint(gc) -- shape1、shape2、座標を描画する
     gc:setColorRGB(231, 231, 231) --灰色
     gc:fillRect(xmin, ymin, xmax, ymax) --灰色(背景)の範囲
     shape1:paint(gc) --shape1を描画
     shape2:paint(gc) --shape2を描画
     gc:setColorRGB(0, 0, 255) --青(座標数字の色)
     gc:setFont("sansserif" , "b", 11) --フォントを設定
     x = gc:drawString("(" .. shape1.xpos..", ".. shape2.ypos .. ")", 50, 0, "top") --座標を文字列として表示
end

function on.arrowLeft() --左矢印キーでshape1を左へ5移動
     shape1:move(-5, 0)
end
function on.arrowRight() --右矢印キーでshape1を右へ5移動
     shape1:move(5, 0)
end
function on.arrowUp() --上矢印キーでshape1を上へ5移動
     shape1:move(0, -5)
end
function on.arrowDown() --下矢印キーでshape1を下へ5移動
     shape1:move(0, 5)
end

function on.mouseDown(wx, wy) -- クリックした位置へshape2を移動する

     shape2:setxy(wx, wy) --shape2の座標を、クリックした座標に設定する
end

-------------------------------------------------------------

(今回の実行例)

f:id:ti-nspire:20141022081022g:plain