Difference between revisions of "Template:Lua programming language"
Jump to navigation
Jump to search
imported>Thelinx |
|||
| Line 1: | Line 1: | ||
| − | + | print("Hello World!") | |
| − | + | function factorial(n) | |
| − | + | if n == 0 then | |
| − | + | return 1 | |
| − | + | else | |
| − | + | return n * factorial(n - 1) | |
| − | + | end | |
| − | + | end | |
| − | + | function factorial2(n) | |
| − | + | return n == 0 and 1 or n * factorial2(n - 1) | |
| − | + | end | |
| − | + | do | |
| − | + | local oldprint = print -- Store current print function as oldprint | |
| − | + | function print(s) -- Redefine print function | |
| − | + | if s == "foo" then | |
| − | + | oldprint("bar") | |
| − | + | else | |
| − | + | oldprint(s) | |
| − | + | end | |
| − | + | end | |
| − | [[ | + | end |
| − | + | function addto(x) | |
| − | [ | + | -- Return a new function that adds x to the argument |
| − | + | return function(y) | |
| + | -- When we refer to the variable x, which is outside of the current | ||
| + | -- scope and whose lifetime is longer than that of this anonymous | ||
| + | -- function, Lua creates a closure. | ||
| + | return x + y | ||
| + | end | ||
| + | end | ||
| + | fourplus = addto(4) | ||
| + | print(fourplus(3)) -- Prints 7 | ||
| + | fibs = { 1, 1 } -- Initial values for fibs[1] and fibs[2]. | ||
| + | setmetatable(fibs, { -- Give fibs some magic behavior. | ||
| + | __index = function(name, n) -- Call this function if fibs[n] does not exist. | ||
| + | name[n] = name[n - 1] + name[n - 2] -- Calculate and memorize fibs[n]. | ||
| + | return name[n] | ||
| + | end | ||
| + | }) | ||
Revision as of 04:19, 13 May 2011
print("Hello World!") function factorial(n)
if n == 0 then return 1 else return n * factorial(n - 1) end
end function factorial2(n)
return n == 0 and 1 or n * factorial2(n - 1)
end do
local oldprint = print -- Store current print function as oldprint
function print(s) -- Redefine print function
if s == "foo" then
oldprint("bar")
else
oldprint(s)
end
end
end function addto(x)
-- Return a new function that adds x to the argument return function(y) -- When we refer to the variable x, which is outside of the current -- scope and whose lifetime is longer than that of this anonymous -- function, Lua creates a closure. return x + y end
end fourplus = addto(4) print(fourplus(3)) -- Prints 7 fibs = { 1, 1 } -- Initial values for fibs[1] and fibs[2]. setmetatable(fibs, { -- Give fibs some magic behavior.
__index = function(name, n) -- Call this function if fibs[n] does not exist. name[n] = name[n - 1] + name[n - 2] -- Calculate and memorize fibs[n]. return name[n] end
})