How does an object reference itself in Lua?

我的梦境 提交于 2019-12-01 16:50:50
Greg Hewgill

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 statement

function t.a.b.c:f (params) body end

is syntactic sugar for

t.a.b.c.f = function (self, params) body end
RBerteig

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

Vousk
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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!