Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

What does making a function a variable do?

Asked by
Discern 1007 Moderation Voter
9 years ago

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?

0
That's exactly the same as saying function thefunction(mhm). You also have your syntax incorrect here, I believe. (should just be thefunction = function(mhm)) Tkdriverx 514 — 9y

1 answer

Log in to vote
2
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

Syntax (Sugar) Overview

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.


Organizational Purpose

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

Function as Values

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.

0
Why do you always overdo it, Blue? Tkdriverx 514 — 9y
0
He makes simple answers beautiful pieces of art BlackJPI 2658 — 9y
Ad

Answer this question