【发布时间】: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。