summaryrefslogtreecommitdiff
path: root/Data/DefaultContent/Libraries/containers/stack.lua
blob: d828c81695ddd45cba4c7bb1c5d3b328d710d1ec (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
--堆栈实现
stack = stack or {}

function stack.create()
    local data = {}

    local function push(v)
        assert(v)
        table.insert(data, v)
    end

    local function pop()
        assert(#data > 0)
        table.remove(data)
    end

    local function peek()
        return #data > 0 and data[#data] or nil
    end

    local function clear()
        for i=1,#data do
            data[i] = nil
        end
    end

    

    local __tostring = function()
        local tmp = {}
        for i,v in ipairs(data) do
            tmp[#data+1 - i] = v
        end
        return table.concat(tmp, ",")
    end

    local __index = function(i_t, key)
        error(">> Dee: Limited access")
    end

    local __len = function()
        return #data
    end

    local __newindex = function(i_t, key, v)
        error(">> Dee: Limited access")
    end

    local __ipairs = function()
        error(">> Dee: Limited access")
    end

    local mt = {__tostring = __tostring, __index = __index, __newindex = __newindex, __ipairs = __ipairs, __pairs = __ipairs, __len = __len}

    local t = {
        push = push,
        pop = pop,
        peek = peek,
        clear = clear
    }

    setmetatable(t, mt)

    return t
end

return stack