2014年10月13日 星期一

LUA Point class example 2

--
-- refine Point class for LUA
--
function class()
  local cls = {}
  cls.__index = cls
  return setmetatable(cls,
    { __call = function (c, ...)
       instance = setmetatable({}, cls)
       if cls.__init then
          cls.__init(instance, ...)
       end
       return instance
      end
    }
  )
end

Point = class()
Point.key_list = {"x","y","z"}

function Point.__index(t,key)
  error("No such Point member or init:"..key ,2)
end

function Point.__newindex(t,key,value)
  for i = 1,#Point.key_list do
    if key == Point.key_list[i] then
       -- t[key] = value
       rawset(t,key,value)
       return
    end 
  end
  error("No such Point member :"..key ,2)
end

function Point:__init(...)
 args = { ... }
 if #args == 3 then
   self.x = args[1]
   self.y = args[2]
   self.z = args[3]
 elseif #args == 2 then
   self.x = args[1]
   self.y = args[2]
 else
    error("2D or 3D only" ,2)  
 end
end

function Point:__tostring()
  local out = ""..self.x..","..self.y
 
  local zz = rawget(self,"z")      
  if zz ~= nil then
     out=out..","..self.z
  end
  return out 
end

--
-- Usage
--

p1 = Point(1,2)
p2 = Point(3,4)

p1.x = 8

x1,y1=p1.x,p1.y
print(string.format("x1,y1=%d,%d",x1,y1))

-- p2 = p1

print(string.format("x2,y2=%d,%d",p2.x,p2.y))
--
local points = {p1,p2}
print("points[1].x=" .. points[1].x)
print("points[2].y=" .. points[2].y)


print("p1="..tostring(p1))
--print("p1="..p1)

p3 = Point(4,5,6)
print("p3="..tostring(p3))

--[[ below is two  error test
print("p1.z="..p1.z)  -- : No such Point member or init:z
p1.xxx = 567          -- : No such Point member :xxx
-- ]]

--
--[[ output
--
x1,y1=8,2
x2,y2=3,4
points[1].x=8
points[2].y=4
p1=8,2
p3=4,5,6
: No such Point member or init:z
: No such Point member :xxx
-- ]]

標籤: , , ,

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁