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

Object Oriented Programming in LUA

Started by chriskevini, 10 August 2012 - 10:10 PM
chriskevini #1
Posted 11 August 2012 - 12:10 AM
I am completely confused right now… This ran in a computer outputs NOTHING


point= {}	   -- THE CLASS
point.new = function(name, x, y)

-- #PRIVATE VARIABLES
local self = {}	   -- Object to return
name = name or "point"
x = x or 0			-- Default if nil
y = y or 0			-- Default if nil
-- #GETTERS
self.getname = function() return name end
self.getx = function() return x end
self.gety = function() return y end

-- #SETTERS
self.setname = function(arg) name = arg end
self.setx = function(arg) x = arg end
self.sety = function(arg) y = arg end

-- #DRAW
self.draw = function ()
  print (name.." = "..x..","..y)
end
return self		 --VERY IMPORTANT, RETURN ALL THE METHODS!
end

derp = {pointA, pointB, pointC}
pointA= point.new("YES", 3, 4)
pointB= point.new("NO", 7, 8)
pointC= point.new("MAYBE", 8, 9)

for i = 1, #derp do
derp[i].draw()
end



But run it twice and it ouputs:


YES = 3,4
NO = 7,8
MAYBE = 8,9


Also, if you duplicate this block of code and run it once


derp = {pointA, pointB, pointC}
pointA= point.new("YES", 3, 4)
pointB= point.new("NO", 7, 8)
pointC= point.new("MAYBE", 8, 9)

It outputs


YES = 3,4
NO = 7,8
MAYBE = 8,9



WAT?

Is there something wrong with OOP in LUA or ComputerCraft?
Or am I doing something wrong?

I got the point 'class' from http://www.troublesh.../lua/luaoop.htm
MysticT #2
Posted 11 August 2012 - 12:19 AM
The problem is that you set the values on the table before defining them, so they are nil and the table is empty. When you run it again, the pointA, pointB and pointC are defined because you defined them as global variables (so they are created the first time you run it).
chriskevini #3
Posted 11 August 2012 - 12:23 AM
The problem is that you set the values on the table before defining them, so they are nil and the table is empty. When you run it again, the pointA, pointB and pointC are defined because you defined them as global variables (so they are created the first time you run it).

How'd I "set the values on the table before defining them"?

Also, doesn't that mean that the table doesn't get destroyed after the program finishes?
MysticT #4
Posted 11 August 2012 - 01:10 AM
Instead of:

derp = {pointA, pointB, pointC}
pointA= point.new("YES", 3, 4)
pointB= point.new("NO", 7, 8)
pointC= point.new("MAYBE", 8, 9)
use:

pointA= point.new("YES", 3, 4)
pointB= point.new("NO", 7, 8)
pointC= point.new("MAYBE", 8, 9)
derp = {pointA, pointB, pointC}

The variables aren't "destroyed" because they are defined as global. Use local so they are collected (by the garbage collector) when the program finishes:

local pointA = point.new("YES", 3, 4)
chriskevini #5
Posted 11 August 2012 - 02:25 AM
Alright thanks!