在Lua中面向对象编程的问题

我创建了一个渲染 Lua 文件,并创建了多个对象。我复制了文件的一小部分。这个“问题”(class)是我有问题的。当创建newBox函数时,当调用registerBox()函数时,this:show()会导致Box:show()中的nil尝试调用错误。但是,我已经玩弄了语法(将一行伸展成多行,以确定哪一行引起了错误),我确信该函数并非导致尝试调用nil,而是this.x或任何this.<var>部分。我没有正确地传递变量吗?请记住,这只是一个片段,所有调用的功能都被省略,所以我不必发布750行代码。我已经对一些事情进行了评论,以帮助您更好地理解我的意思,以便您不必太详细地逐行阅读代码。

-- Box Class

function newBox(x,y,z,w,h,t,b,c)
  local this = setmetatable({}, Box)
  this.x = x
  this.y = y
  this.z = z
  this.w = w
  this.h = h
  this.t = t
  this.b = b
  this.c = c
  this:show()
  this.v = true

  return this
end

例如,当创建一个新对象时,这将被调用local obj = newBox( ... )

function Box:render()
  rasterBox(this.x,this.y,this.w,this.h)
  renderBox(this.x,this.y,this.w,this.h)
end

这将呈现框,不用担心,这一切都很好......

function Box:move(x,y,z)
  this:hide()
  this.x = x
  this.y = y
  if z then
    this.z = z
  end
  this:show()
end

function Box:resize(w,h)
  this:hide()
  this.w = w
  this.h = h
  this:show()
end

function Box:pattern(t,b,c)
  this:hide()
  this.t = t
  this.b = b
  this.c = c
  this:show()
end

上面的代码不应该有任何问题,应该......

function Box:show()
  registerBox(this.x,this.y,this.z,this.w,this.h,this.t,this.b,this.c) -- CALL NIL ERROR
  this.v = true
  this:render()
end

上面的函数在创建对象时调用> this:show()它不是RegisterBox函数,而是实际的this.[var]参数。以下是该代码的其余部分。尽管不确定下面的代码是否会导致任何问题。

function Box:hide()
  unregisterBox(this.x,this.y,this.z,this.w,this.h)
  this.v = false
  this:render()
end

function Box:getPosition()
  return this.x,this.y,this.z
end

function Box:getPattern()
  return this.t,this.b,this.c
end

function Box:getSize()
  return this.w,this.h
end

function Box:destroy()
  this:hide()
  this = nil
end
点赞
用户1601606
用户1601606

正如@user1095108所说,lua 中没有这个关键字,类似于“this”的隐藏参数被称为self

所有的面向对象机制在这里都有很好的描述,尝试使用简单的例子进行实验,理解它的工作原理,它很容易理解。简而言之,冒号是一个语法糖,在函数声明或调用时添加额外的参数。参数称为self,它是左侧函数调用的对象引用。

另外,这种写法是没有意义的:

function Box:destroy()
  this:hide()
  this = nil -- Here you assign nil to local variable, passed as parameter.
end

如果你要释放某个对象,你应该确保所有对它的引用都没有被引用,包括调用者的对象。参数将自动被释放,因为它们是局部变量。

2014-01-30 11:54:49