Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Lua
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==== Inheritance ==== Lua supports using metatables to give Lua class inheritance.<ref>{{cite book|title=Programming in Lua, 4th Edition|page=165|author=Roberto Ierusalimschy}}</ref> In this example, we allow vectors to have their values multiplied by a constant in a derived class. <syntaxhighlight lang="lua"> local Vector = {} Vector.__index = Vector function Vector:new(x, y, z) -- The constructor -- Here, self refers to whatever class's "new" -- method we call. In a derived class, self will -- be the derived class; in the Vector class, self -- will be Vector return setmetatable({x = x, y = y, z = z}, self) end function Vector:magnitude() -- Another method -- Reference the implicit object using self return math.sqrt(self.x^2 + self.y^2 + self.z^2) end -- Example of class inheritance local VectorMult = {} VectorMult.__index = VectorMult setmetatable(VectorMult, Vector) -- Make VectorMult a child of Vector function VectorMult:multiply(value) self.x = self.x * value self.y = self.y * value self.z = self.z * value return self end local vec = VectorMult:new(0, 1, 0) -- Create a vector print(vec:magnitude()) -- Call a method (output: 1) print(vec.y) -- Access a member variable (output: 1) vec:multiply(2) -- Multiply all components of vector by 2 print(vec.y) -- Access member again (output: 2) </syntaxhighlight> Lua also supports [[multiple inheritance]]; {{code|language=lua|__index}} can either be a function or a table.<ref>{{Cite web|title=Programming in Lua : 16.3|url=https://www.lua.org/pil/16.3.html|access-date=2021-09-16|website=Lua}}</ref> [[Operator overloading]] can also be done; Lua metatables can have elements such as {{code|language=lua|__add}}, {{code|language=lua|__sub}} and so on.<ref>{{Cite web|title= Metamethods Tutorial|url=http://lua-users.org/wiki/MetamethodsTutorial|access-date=2021-09-16|website=lua-users wiki |url-status=dead |archive-url=https://web.archive.org/web/20210916182214/http://lua-users.org/wiki/MetamethodsTutorial |archive-date=September 16, 2021}}</ref>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)