Paste: noob lua question

Author: erg
Mode: factor
Date: Sun, 24 Jul 2011 06:06:24
Plain Text |
run: lua deque.lua

fails with:

lua: deque.lua:38: attempt to call method 'push_front' (a nil value)
stack traceback:
	deque.lua:38: in main chunk
	[C]: ?

--START--


Deque = {}

function Deque:new ()
    return {first = 0, last = -1}
end

function Deque:push_front (value)
    local first = self.first - 1
    self.first = first
    self[first] = value
end

function Deque:pop_front ()
    local first = self.first
    if first > self.last then error("list is empty") end
    local value = self[first]
    self[first] = nil -- to allow garbage collection
    self.first = first + 1
    return value
end

--fails...
local dee = Deque:new()
dee:push_front(5)
print(dee:pop_front())



--[[ this works:
local d = Deque.new()
Deque.push_front(d,5)
print(Deque.pop_front(d))
]]--

Annotation: the fix (lol)

Author: erg
Mode: factor
Date: Sun, 24 Jul 2011 06:38:55
Plain Text |
function Deque:new ()
    return setmetatable({first = 0, last = -1}, {__index=Deque})
end

New Annotation

Summary:
Author:
Mode:
Body: