Posted 06 February 2014 - 08:40 AM
Hey guys, i am started to use OOP in lua and tried to implement a heap. Everything works fine in "pure lua" but i have problems to use it in ComputerCraft. I created a file called "Heap" and load it with os.loadAPI("Heap"). To create a new object i have to call the constructor "Heap()" or the function "Heap.new()". Both return an "attempt to call nil" error. However if i rename the Method "Heap.new()" to "Heapnew()", a call of "Heapnew()" works, but the constructor is still broken. Is there a way to get the constructor "Heap()" working, so i dont have to use the ugly function call "Heapnew()" ?
------------------------------File Heap------------------------------------
local Heap = {}
Heap.__index = Heap
setmetatable(Heap, {
__call = function (cls, ...)
return cls.new(...)
end,
})
--"Constructor"
function Heap.new()
local self = setmetatable({}, Heap);
self.nodes = {};
self.currPosition = 1;
self.nodes[self.currPosition] = HeapNode(nil,nil);
return self;
end
--modified "Constructor"
function Heapnew()
local self = setmetatable({}, Heap);
self.nodes = {};
self.currPosition = 1;
self.nodes[self.currPosition] = HeapNode(nil,nil);
return self;
end
-------------------------File test--------------------------------------------
os.loadAPI("Heap")
myHeap = Heap.Heap() -- throws attempt to call nil
myHeap = Heap.Heap.new() -- throws attempt to call nil
myHeap = Heap.Heapnew() -- works