尝试索引本地“自我"(nil值) [英] Attempt to index local 'self' (a nil value)

查看:114
本文介绍了尝试索引本地“自我"(nil值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在上课时遇到问题.我遇到以下错误: 尝试索引本地自我"(nil值) 当我调用下面的类的getter方法时. Item.lua文件:

I have a problem with classes. I got below error: Attempt to index local 'self' (a nil value) When I call the getter method of below class. Item.lua file:

require "classlib"
Item = class("Item")

function Item:__init()
    self.interval = 1
end

function Item:getInterval()
    return self.interval
end

我这样称呼这个吸气功能:

I'm calling this getter function like this:

dofile("../src/item.lua")

item = Item()

function test_item()
    assert_equal(1, item.getInterval())
end

这是什么问题?

亲切的问候...

推荐答案

通常,您应该通过:调用成员函数.

In general, you should call member functions by :.

在Lua中,冒号(:)代表函数的调用,将self作为第一个参数.

In Lua, colon (:) represents a call of a function, supplying self as the first parameter.

因此

A:foo()

大约等于

A.foo(A)

如果未在A.foo()中指定A,则函数的主体将尝试引用self参数,该参数既没有明确填充也没有隐式填充.

If you don't specify A as in A.foo(), the body of the function will try to reference self parameter, which hasn't been filled neither explicitly nor implicitly.

请注意,如果您从成员函数的 inside 中调用它,则self将已经可用:

Note that if you call it from inside of the member function, self will be already available:

-- inside foo()
-- these two are analogous
self:bar()
self.bar(self)

所有这些信息都可以在Lua的所有优秀书籍/教程中找到.

All of this information you'll find in any good Lua book/tutorial.

这篇关于尝试索引本地“自我"(nil值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆