如何正确使用self在这个示例中打印字符串

在这个 MWE 中,我试图写一个在 lua 中的函数,当调用它时,它会打印一些文本以及调用函数的字符串。

为了实现这个目的,我使用了 self 来打印字符串,但实际上它返回了一个 nil 值。我该如何在这个示例中正确使用 self,并如何完成这样的任务呢?

str = "Some text on the string"

function string.add()
    print("Hope it prints the string besides too",self)
end

str:add()

输出如下:

Hope it prints the string besides too nil

我想要的是:

Hope it prints the string besides too Some text on the string

点赞
用户9922866
用户9922866

在你的函数中,string.add(self) 相当于 string:add()。在后者中,它是字符串类的成员函数或方法,self 是隐式的第一个参数。这与 Python 中的类类似,其中 self 是每个成员函数的第一个参数。

-- 注意 self 参数。
function string.add(self)
    print("Hope it prints the string besides too", self)
    return
end

str = "Just some text on the string"
str:add()

另外,如果你在调用 str:add() 时通过 C API 将 Lua 栈中的项暴露出来,str 将成为栈上的第一个项,即索引为 1 的元素。项目按传递给函数的顺序推入堆栈。

print("hello", "there,", "friend")

在这个例子中,"hello" 是堆栈上的第一个参数,"there," 是第二个参数,"friend" 是第三个参数。在你的 add 函数中,写成 str:add()string.add(str)self 指的是 str,是 Lua 栈上的第一项。使用索引运算符定义成员函数,例如 string.add 的形式,可以提供灵活性,因为可以同时使用显式 self 和隐式 self 的形式。

2020-01-02 08:18:16