Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

What does making a function a variable do?

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?

1 comment

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))

1 answer

✓ Accepted answer

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.

2 comments

0

Why do you always overdo it, Blue?

0

He makes simple answers beautiful pieces of art

This discussion is preserved as it was. New answers, comments, and votes are closed.