Reputation: 231
In this MWE I'm trying to write a function in lua
that when it is called it prints some text alongside the string that called the function.
For this to work I used self
to print the string, but it actually returns a nil
value. How do I correctly use the self
in this example and how do I archive such task?
str = "Some text on the string"
function string.add()
print("Hope it prints the string besides too",self)
end
str:add()
The output is the following:
Hope it prints the string besides too nil
What I would like to have:
Hope it prints the string besides too Some text on the string
Upvotes: 1
Views: 525
Reputation: 484
In the case of your function, string.add(self)
is equivalent to string:add()
. In the latter version, which is a member function--or method--of the string class, self
is the implicit first parameter. This is similar to classes in Python, where self
is the first parameter of every member function.
-- 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()
As a side note, if you were to expose the items on the Lua stack through the C API when you call str:add()
, str
would be the first item on the stack, that is, the element at index 1
. Items are pushed on to the stack in the order that they are passed to functions.
print("hello", "there,", "friend")
In this example, "hello"
is the first argument on the stack, "there,"
is the second, and "friend"
is the third. In the case of your add
function--written as str:add()
or string.add(str)
--self
, which refers to str
, is the first item on the Lua stack. Defining member functions with the index operator, as of the form string.add
, allows for flexibility, as one can use the form with the explicit self
and the form with the implicit self
.
Upvotes: 1