【问题标题】:Attempt to index global 'self' (a nil value) _尝试索引全局“自我”(零值)_
【发布时间】:2015-02-18 02:45:17
【问题描述】:

我运行了这段代码,它给了我一个错误尝试索引全局“自我”(一个零值)

hook.Add("Think", "Cooking", function()
    local Position = self:GetPos() + self:GetAngles():Up()*20
    local rawFood = ents.FindByName("my_raw_food")
    for k, v in pairs(rawFood) do
        if(Position:Distance(v:GetPos()) <= 25) then 
        v:Remove()
        timer.Create(self:EntIndex() .. "my_food", 5, 1, function() self:createFood() end)
        end
    end
end )

【问题讨论】:

  • 也许你需要写function(self)而不是function()

标签: lua null self


【解决方案1】:

如果不看更多代码很难说,尤其是围绕代码的范围。

但听起来“自我”不存在于范围内。它应该作为函数的参数提供:

hook.Add("Think", "Cooking", function(self)
  print(self)    -- uses the 'self' parameter
end)

或者它应该在声明函数的范围内可用,它将成为闭包的一部分:

function MyClass.addHook(self)    -- same as MyClass:addHook()
  hook.Add("Think", "Cooking", function()
    print(self)    -- uses the 'self' in scope (la MyClass instace)
  end)

尽管self 当然可以是nil,即使它已在作用域中声明。调用MyClassInstance.addHook() 而不是MyClassInstance:addHook() 是最常见的。

【讨论】:

  • """MyClassInstance.addHook() 而不是 MyClassInstance:addHook() 是最常见的""""。这对我有用
【解决方案2】:

self 在使用文档16 - Object-Oriented Programming 中描述的面向对象编程时使用。

为了使用 self ,您必须将其作为第一个参数隐式传递。

我是说……

myObject = { id = 1 }
function myObject:hello( name )
  print( "hello " .. name .. " I'm object id : " .. tostring( self.id ) )
end

// Using the . char the object must be the first argument
myObject.hello( myObject, "world" )

// Using the : char the obect is automatically set as the first arg
myObject:hello( "world" ) 

所以在你的代码中,我猜你应该使用 : char。

hook:add(...)

【讨论】:

  • 我相信如果hook.Add("Think", ...) 调用了一个期望self 作为第一个参数的函数,你会得到一个错误,关于selfstring(不是零值)。
猜你喜欢
  • 2020-04-27
  • 1970-01-01
  • 2020-11-03
  • 2017-12-20
  • 2013-06-07
  • 2020-03-08
  • 2013-09-04
  • 1970-01-01
相关资源
最近更新 更多