Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- regular function
- function sayHello (recipient)
- print('Hello, '..recipient)
- end
- sayHello('Roberto')
- -- anonymous function (exactly the same as above)
- local sayHello = function (recipient)
- print('Hello, '..recipient)
- end
- -- function on an object
- local cat = {}
- function cat.sayHello ()
- print('Meow')
- end
- cat.sayHello();
- -- self-executing anonymous function
- (function (recipient)
- print('Hello, '..recipient) --> Hello Luiz
- end)('Luiz')
- -- Multiple return values
- function getCoordinates()
- return 12, 55, 123
- end
- local x, y, z = getCoordinates()
- print(x, y, z) --> 12 55 123
- -- varargs
- function sayAllsorts(...)
- print(...)
- end
- sayAllsorts('Lua', 5.1, 'on the Web') --> Lua 5.1 on the Web
- -- mix 'n' match varargs
- function tail (h, ...)
- return ...
- end
- print(tail (1, 2 ,3)) --> 2, 3
- -- function calls that pass either a single string or single object don't
- -- require brackets
- print 'Hello, Waldemar'
- print { foo = 'bar' }
- -- functions are first class objects
- function doStuffWithAThing (thing, ...)
- thing (...)
- end
- doStuffWithAThing(print, 1, 2, 3)
- a = {}
- doStuffWithAThing(table.insert, a, 'moo')
- print(a[1])
- -- the colon is just syntatic sugar
- local cat = { name = 'Ruby', food = 'Felix' }
- function cat.getName (self) -- there is no such thing as "self", you have to
- -- provide it
- return self.name
- end
- print(cat.getName(cat)) -- pass the cat in
- -- use a colon instead and Lua will automatically pass what's before the colon
- -- as the first argument
- print(cat:getName()) -- this is exactly the same as the previous call
- -- better still, you can clean up that function definition with a colon too; Lua
- -- will automatically add a "self" parameter at the front
- function cat:getFood () -- there is no such thing as "self", you have to
- -- provide it
- return self.food
- end
- print(cat:getFood())
- print(cat.getFood(cat)) -- both these calls are the same.
Add Comment
Please, Sign In to add comment