【问题标题】:How to properly use self to print the string in this example本例中如何正确使用self打印字符串
【发布时间】:2020-04-19 13:10:53
【问题描述】:

在这个 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()

输出如下:

希望它打印出的字符串除了 nil 之外

我想要什么:

希望它打印字符串之外的字符串还有一些文本

【问题讨论】:

  • function string:add()替换function string.add()
  • afaik 你也可以只做函数 string.add(self)。为我工作。虽然这可能是不好的做法。
  • 谢谢你,@EgorSkriptunoff 这真的很有帮助。
  • @Levy function string:add()function string.add(self)see 的另一种拼写形式

标签: function lua self


【解决方案1】:

对于您的函数,string.add(self) 等效于 string:add()。在后一个版本中,它是字符串类的成员函数或方法,self 是隐式的第一个参数。这类似于 Python 中的类,其中self 是每个成员函数的第一个参数。

-- Notice the self parameter.
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 将是堆栈上的第一项,即索引@ 处的元素987654328@。项按传递给函数的顺序被压入堆栈。

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

在本例中,"hello" 是堆栈上的第一个参数,"there," 是第二个,"friend" 是第三个。对于你的add 函数——写成str:add()string.add(str)--self,指的是str,是Lua 堆栈上的第一项。使用索引运算符定义成员函数,如 string.add 形式,允许灵活性,因为可以使用具有显式 self 的形式和具有隐式 self 的形式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 1970-01-01
    相关资源
    最近更新 更多