Lua 对象 - 构造函数中的错误初始化

标签 lua coronasdk

我是 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/

相关文章:

lua - LUA meta tables 可以协助检测 nilling object 吗?

lua - 将文件逐行读入数组

lua - Corona SDK 或 Lua 是否有可用的 'eval' 函数?

android - 我玩过各种物理设置,但对象仍然感觉太 "floaty"

Lua 错误尝试索引全局 nil 值

C++ - 从没有自定义 .lib 文件的 Lua C 模块调用 Lua 函数

lua - 我可以从通过 string.dump() 检索的 lua 字节码中得到什么?

lua <eof> 预计接近结束

android - Corona SDK 中的转换

function - 如何解决 Lua 中的函数依赖循环?