【问题标题】:Issue with Object Oriented Programming in LuaLua 中的面向对象编程问题
【发布时间】:2014-01-31 20:33:08
【问题描述】:

我创建了一个渲染 Lua 文件,并创建了多个对象,我复制了该文件的一个小 sn-p。这是我遇到问题的对象(类)。当newBox 函数被创建时,this:show() 在函数registerBox() 被调用时导致Box:show() 中的错误。尝试调用 nil

但是我已经使用了一些语法(将一行延伸到多行以确定导致错误的行的哪一部分)我知道该函数不会导致尝试调用 nil ,它是this.x 或任何this.<var> 我没有正确传递变量吗?请记住,这只是一个 sn-p,所有调用的函数都被省略了,所以我不必发布 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

在创建新对象时调用,例如本地 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

【问题讨论】:

  • 尝试使用self 而不是this

标签: oop lua


【解决方案1】:

正如@user1095108所说,lua中没有this,隐藏,this-like,参数叫做self

here 对所有类似 OOP 的机制进行了详细描述,尝试使用简单的示例进行游戏,以了解其工作原理,这很容易。简而言之,冒号是函数声明或调用时额外参数的语法糖。 Param 被称为 self,它是一个对象,位于函数调用的左侧。对它的引用被传递给函数。

这样做也没用

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

如果你想释放一些对象,你应该确保对它的所有引用都是未引用的,包括来自调用者的对象。参数将自动释放,因为它们是 local

【讨论】:

  • nil 错误发生正是因为您使用了this。用self搜索并替换每个this,你应该没问题。编辑:@Seagull,这是--,而不是// ;)
  • 哦,好吧,我认为变量无关紧要,而且我在同一个文件中有多个对象(类),self变量不会与其他变量冲突,因为它是本地的吗?
  • @user3214283 是的。 self 是本地的,并且隐式声明为函数的第一个参数。它也会影响所有其他全局自变量。
  • @HenrikIlgen 哎呀。谢谢!我的生活中有太多类似 C 的语言 ;)
猜你喜欢
  • 2022-01-05
  • 1970-01-01
  • 2017-07-05
  • 1970-01-01
  • 2022-01-20
  • 2011-01-23
  • 2015-04-22
  • 2021-06-10
  • 2010-09-18
相关资源
最近更新 更多