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!
=== Metatables === Extensible semantics is a key feature of Lua, and the [[#Metatables|metatable]] concept allows powerful customization of tables. The following example demonstrates an "infinite" table. For any <code>n</code>, <code>fibs[n]</code> will give the <code>n</code>-th [[Fibonacci number]] using [[dynamic programming]] and [[memoization]]. <syntaxhighlight lang="lua"> fibs = { 1, 1 } -- Initial values for fibs[1] and fibs[2]. setmetatable(fibs, { __index = function(values, n) --[[__index is a function predefined by Lua, it is called if key "n" does not exist.]] values[n] = values[n - 1] + values[n - 2] -- Calculate and memoize fibs[n]. return values[n] end }) </syntaxhighlight>
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)