From 5335b0669f5c7c96bbb532af53b499c3f73a68c7 Mon Sep 17 00:00:00 2001 From: sanine Date: Fri, 25 Feb 2022 09:33:27 -0600 Subject: add class function and geom.square constructor --- city/geometry-test.lua | 29 +++++++++++++++++++++++++++++ city/geometry.lua | 33 ++++++++++++++++++++++++++++----- 2 files changed, 57 insertions(+), 5 deletions(-) (limited to 'city') diff --git a/city/geometry-test.lua b/city/geometry-test.lua index ab3265d..3fedae6 100644 --- a/city/geometry-test.lua +++ b/city/geometry-test.lua @@ -1,6 +1,13 @@ local test = require('minunit').test local geom = require 'geometry' + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +-- +-- geom.point tests +-- +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + test( 'create point object', function() @@ -22,3 +29,25 @@ test( assert(a:distance_to(a) == 0) end ) + + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +-- +-- geom.square tests +-- +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +test( + 'create square object', + function() + local s = geom.square(geom.point(0, 0), 1) + assert(s.center.x == 0) + assert(s.center.y == 0) + assert(s.span == 1) + + assert(s.x.min == -0.5) + assert(s.x.max == 0.5) + assert(s.y.min == -0.5) + assert(s.y.max == 0.5) + end +) diff --git a/city/geometry.lua b/city/geometry.lua index 47e6a78..a775213 100644 --- a/city/geometry.lua +++ b/city/geometry.lua @@ -1,17 +1,22 @@ local geom = {} +local function class(tbl) + setmetatable(tbl, tbl) + return tbl +end + -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- point -- -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -local point = { - __call = function(_, x, y) +geom.point = class{ + __call = function(this, x, y) local pt = {} pt.x = x pt.y = y - setmetatable(pt, {__index=_}) + setmetatable(pt, {__index=this}) return pt end, @@ -21,8 +26,26 @@ local point = { return math.sqrt(d_x*d_x + d_y*d_y) end, } -setmetatable(point, point) -geom.point = point +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +-- +-- square +-- +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +geom.square = class{ + __call = function(this, center, span) + local square = {} + square.center = center + square.span = span + square.x = this.axis_range(center.x, span/2) + square.y = this.axis_range(center.y, span/2) + setmetatable(square, {__index=this}) + return square + end, + + axis_range = function(c, r) return {min=c-r, max=c+r} end, +} + return geom -- cgit v1.2.1