我是 Lua 和 Corona 的初学者。我有一个名为 Square 的类,我想初始化它。这是我的课:
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()
问题是 hello() 函数打印错误。它打印
Hello 3 4 0
不应该打印吗
Hello 2 3 4
?
为什么x用y的值初始化,y用colorNumber初始化,colorNumber为0?
谢谢。
问候, 塞尔维亚人
最佳答案
使用 square = Square:init(2,3,4)
因为使用 :
语法定义或调用的函数是方法并采用隐藏参数 self
:Square:init(2,3,4)
与 Square.init(Square,2,3,4)
相同。
关于Lua 对象 - 构造函数中的错误初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36246743/