So if I have a code with this in it:
thefunction = function bleh(mhm) --does code here end
Why would I put "thefunction" there, and how would I use it?
What you have written won't compile.
input:1: '(' expected near 'bleh'
(You can either have the name left of the equals sign or right before the function parameters -- but you can't do both)
The following two snippets are the same code more or less:
thefunction = function(mhm) --does code here end
function thefunction(mhm) --does code here end
That is, the normal function definition is actually making a variable.
Beyond functional differences, this may be clearer for organizational purposes.
You can make it clearer that something belongs to a particular object by using consistent syntax:
t.color = "red" t.name = "ball" t.action = function() print("HI") end t.gravity = 0.2
(rather than interrupting this with the function definition:
t.color = "red" t.name = "ball" function t.action() print("HI") end t.gravity = 0.2
It also allows to make aliases for functions, e.g.,
function MakeColor(r,g,b) return Color3.new(r * 255, g * 255, b * 255) end MakeColour = MakeColor
Making functions variables can be useful in many cases. A simple example is as a function parameter to a map
function:
function map(tab, fun) for i,v in pairs(tab) do tab[i] = fun(v) end end local t = { 1 , 4, 9, 15} map(t, math.sqrt ) print(table.concat(t,", ")) -- 1, 2, 3, 3.8729833462074
Some examples of built-in functions which use functions as parameters are coroutine.create
, coroutine.wrap
, string.dump
, table.sort
, and delay
.
coroutine.wrap
also happens to return a function which you would probably write to a variable.