尝试索引全局'self'(零值)_

1 null lua self

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

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 )
Run Code Online (Sandbox Code Playgroud)

Cal*_*inE 6

如果没有看到更多的代码,特别是代码的范围,很难说.

但听起来"范围内"并不存在"自我".它应该作为参数提供给函数:

hook.Add("Think", "Cooking", function(self)
  print(self)    -- uses the 'self' parameter
end)
Run Code Online (Sandbox Code Playgroud)

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

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

虽然,self当然可以nil在范围内声明.呼叫MyClassInstance.addHook()代替MyClassInstance:addHook()是最常见的.