C# has this
and VB has ME
. What is the Lua equivalent?
I am trying to reference the parent of the script class in Roblox.
From the Lua documentation section 2.5.9, the self reference is usually self
:
The colon syntax is used for defining methods, that is, functions that have an implicit extra parameter
self
. Thus, the statementfunction t.a.b.c:f (params) body end
is syntactic sugar for
t.a.b.c.f = function (self, params) body end
As Greg pointed out already, the name you are looking for is self
.
However, be aware that Lua is not an OOP language any more than it is a purely procedural or functional language. It simply provides all the low level mechanisms to implement an OOP design. One of the design principles has been expressed as to "provide mechanism, not policy". Because of that, there is no way to guarantee that the environment you are running in even uses inheritance, or that you could find a parent for any given object.
It would be a good idea to review the sections of the Lua manual, Programming in Lua, and the Wiki that relate to OOP features:
- Lua Manual, especially sections 2.5.8, 2.5.9 and 2.8.
- PiL Chapter 16, linked to the online copy of the first edition, which was written at the time of Lua 5.0. Read the online copy, but be aware that the current version of Lua is different enough that buying the 2nd edition is highly recommended.)
- Lua Wiki on OOP, especially the tutorial and the article on simple classes.
In Lua, you'll want the "self" value. However, you're using ROBLOX, which is sandboxed. Each script is run in it's own thread, and to reference the script, you'll need to use "script", i.e. script.Parent
local Table = {}
Table.Var = "Testing"
function Table:Test()
print(self.Var)
end
Table:Test()
or
local Table = {}
Table.Var = "Testing"
function Table.Test(self)
print(self.Var)
end
Both function will do the same exact thing.
--Edit--
That only work with tables. If you are trying to get the parent of the script you need to use script.Parent
--Note script.Parent would return where the script is located. If you add another parent, script.Parent.Parent, it would return the parent of the parent, and so on.
来源:https://stackoverflow.com/questions/1066886/how-does-an-object-reference-itself-in-lua