Jump to content

Template:Lua programming language

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 99.184.73.79 (talk) at 04:19, 13 May 2011. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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

})