This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Independent's profile picture

Problem with constructor call in LUA

Started by Independent, 06 February 2014 - 07:40 AM
Independent #1
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
CometWolf #2
Posted 06 February 2014 - 10:31 AM
I don't think you quite understand how os.loadAPI works. It will put all non-local variables in a global table with the same name as the file loaded, so using os.loadAPI"/Heap" on your file would create the table Heap with the function Heapnew. It would skip the table Heap altogether, and thus also Heap.new. This is alo why Heap.Heap() dosen't work, since there is no metatable either.
Edited on 06 February 2014 - 09:57 AM