【问题标题】:Error when attempting to call function in different lua file (function is a nil value)尝试在不同的 lua 文件中调用函数时出错(函数为 nil 值)
【发布时间】:2014-04-12 10:49:53
【问题描述】:

当我尝试在我尝试制作的盒子对撞机对象中调用函数时,我收到以下错误。

错误:

main.lua:26: 尝试调用字段“更新”(一个零值)

追溯

main.lua:26: 在函数“更新”中 [C]: 在函数'xpcall'中

代码:

main.lua

require("BoxCollider")

local s1 = {}
s1.x = 10
s1.y = 10
s1.w = 10
s1.h = 10
s1.collider = BoxCollider.new(s1.x,s1.y,s1.w,s1.h)

test = BoxCollider.new(40, 7,15,15)

function love.load()

end

function love.update(dt)

if love.keyboard.isDown("d") then s1.x = s1.x + 100 * dt end    
---[[   
s1.collider:Update(s1.x,s1.y)

if s1.collider:CheckCollisions(test) then
    s1.x = 10
end
--]]
end

function love.draw()

love.graphics.rectangle("fill", s1.x, s1.y, s1.w, s1.h)
love.graphics.rectangle("fill", 40, 7, 15,15)

end

BoxCollider.lua

BoxCollider = {}
BoxCollider._index = BoxCollider


--x is the x point of the collider, should be equal to the object's x point if the box        is for an object
--y is the y point of the collider, should be equal to the object's x point if the box is for an object
--w is the width of the box
--h is the height of the box

function BoxCollider.new(x,y,w,h)
return setmetatable({x = x or 0, y = y or 0, w = w or 0, h = h or 0},BoxCollider)
end

function BoxCollider:CheckCollisions( v )

return self.x < (v.x + v.h) and  v.x < (self.x + self.w) and self.y  < (v.y+v.h) and v.y < (self.y+self.h)  

end

function BoxCollider:reSize(nw,nh)
self.w = nw
self.h = nh

end

function BoxCollider:Update(nx,ny)
self.x = nx
self.y = ny
end

【问题讨论】:

  • s1.collider.Update 更改为s1.collider:Update
  • 感谢回复,试过了,还是不行。不过我更改了帖子中的代码,因为它本来应该是这样的。

标签: oop function lua


【解决方案1】:

我想你只是忘记了 BoxCollider.__index 中的一个额外的下划线。只有一个下划线 ._index,当 :Update 被调用但未找到时,不会搜索 BoxCollider 方法。

【讨论】:

  • 我很确定这是正确答案,所以应该这样标记。
猜你喜欢
  • 1970-01-01
  • 2018-07-11
  • 2011-07-30
  • 2012-08-14
  • 2010-10-15
  • 2021-09-29
  • 2018-05-30
  • 1970-01-01
  • 2018-09-16
相关资源
最近更新 更多