summaryrefslogtreecommitdiff
path: root/Data/DefaultContent/Libraries/middleclass/spec/metamethods_lua_5_2.lua
blob: 2ea6c9b030e0b6f287778c8db29dfbe05dcc28ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
local class = require 'middleclass'

local it = require('busted').it
local describe = require('busted').describe
local before_each = require('busted').before_each
local assert = require('busted').assert

describe('Lua 5.2 Metamethods', function()
  local Vector, v
  before_each(function()
    Vector= class('Vector')
    function Vector.initialize(a,x,y,z) a.x, a.y, a.z = x,y,z end
    function Vector.__eq(a,b)     return a.x==b.x and a.y==b.y and a.z==b.z end

    function Vector.__len(a)    return 3 end
    function Vector.__pairs(a)
      local t = {x=a.x,y=a.y,z=a.z}
      return coroutine.wrap(function()
        for k,val in pairs(t) do
          coroutine.yield(k,val)
        end
      end)
    end
    function Vector.__ipairs(a)
      local t = {a.x,a.y,a.z}
      return coroutine.wrap(function()
        for k,val in ipairs(t) do
          coroutine.yield(k,val)
        end
      end)
    end

    v = Vector:new(1,2,3)
  end)

  it('implements __len', function()
    assert.equal(#v, 3)
  end)

  it('implements __pairs',function()
    local output = {}
    for k,val in pairs(v) do
      output[k] = val
    end
    assert.are.same(output,{x=1,y=2,z=3})
  end)

  it('implements __ipairs',function()
    local output = {}
    for _,i in ipairs(v) do
      output[#output+1] = i
    end
    assert.are.same(output,{1,2,3})
  end)

  describe('Inherited Metamethods', function()
    local Vector2, v2
    before_each(function()
      Vector2= class('Vector2', Vector)
      function Vector2:initialize(x,y,z) Vector.initialize(self,x,y,z) end

      v2 = Vector2:new(1,2,3)
    end)

    it('implements __len', function()
      assert.equal(#v2, 3)
    end)

    it('implements __pairs',function()
      local output = {}
      for k,val in pairs(v2) do
        output[k] = val
      end
      assert.are.same(output,{x=1,y=2,z=3})
    end)

    it('implements __ipairs',function()
      local output = {}
      for _,i in ipairs(v2) do
        output[#output+1] = i
      end
      assert.are.same(output,{1,2,3})
    end)
  end)
end)