Serban Stoenescu
Serban Stoenescu

Reputation: 3886

Lua object - bad initialization in constructor

I am a beginner in Lua and Corona. I have a class called Square, which I want to initialize. This is my class:

Square = {x=0, y=0, colorNumber=0}
Square.__index = Square

function Square:init(x,y,colorNumber)
   local square = {}             -- our new object
   setmetatable(square,Square) 
   square.x = x      -- initialize our object
   square.y = y      -- initialize our object
   square.colorNumber = colorNumber      -- initialize our object
   return square
end

function Square:hello()
print ("Hello "..self.x.." "..self.y.." "..self.colorNumber)
local n = 10
local t0 = clock()
  while clock() - t0 <= n do end
end

-- create and use a Square
square = Square.init(2,3,4)
square:hello()

The problem is that the hello() function prints wrong. It prints

Hello 3 4 0

Shouldn't it print

Hello 2 3 4

?

Why is x initialized with the value of y, y with colorNumber, and colorNumber 0?

Thanks.

Regards, Serban

Upvotes: 2

Views: 572

Answers (1)

lhf
lhf

Reputation: 72312

Use square = Square:init(2,3,4) because functions defined or called with the : syntax are methods and take a hidden argument self: Square:init(2,3,4) is the same as Square.init(Square,2,3,4).

Upvotes: 2

Related Questions