lua 2d/3d point class
--
-- define Point class for LUA
--
Point = {}
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.new(...)
local pt = {}
args = { ... }
if #args == 3 then
pt.x = args[1]
pt.y = args[2]
pt.z = args[3]
elseif #args == 2 then
pt.x = args[1]
pt.y = args[2]
else
error("2D or 3D only" ,2)
end
setmetatable(pt,Point)
return pt
end
--
-- Usage
--
p1 = Point.new(1,2)
p2 = Point.new(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)
-- [[ 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
: No such Point member or init:z
: No such Point member :xxx
-- ]]
-- define Point class for LUA
--
Point = {}
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.new(...)
local pt = {}
args = { ... }
if #args == 3 then
pt.x = args[1]
pt.y = args[2]
pt.z = args[3]
elseif #args == 2 then
pt.x = args[1]
pt.y = args[2]
else
error("2D or 3D only" ,2)
end
setmetatable(pt,Point)
return pt
end
--
-- Usage
--
p1 = Point.new(1,2)
p2 = Point.new(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)
-- [[ 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
: No such Point member or init:z
: No such Point member :xxx
-- ]]
0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁