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

What are the Differences between "Local Function" and "Function"? [closed]

Asked by
woodengop 1134 Moderation Voter
10 years ago

I know from all my studying that a FunctionFires an Event, But what is the Difference between: Local Function, and a Regular Function?

NOTE: The ROBLOX Wiki did NOT Provide an Answer for this.

0
I guess that local functions are not stored in the server while normal functions are. I'm not so sure though fahmisack123 385 — 10y
0
You go to the wiki to find out, and then you script it. yoshiegg6 176 — 10y
5
yoshi, I just said that the ROBLOX Wiki did not provide an answer. woodengop 1134 — 10y

Locked by woodengop and adark

This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.

Why was this question closed?

3 answers

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

adark missed the biggest practical different between local functions and not.

Global variables can be used lexically (in order in source) before they were declared. For instance,

1function blah()
2    print( a ) -- where a is a global (not local) variable
3end
4 
5a = 5
6blah()
7-- 5

local variables are only usable after them (lexically -- in source order):

1local a = 5
2blah()
3-- nil

The same applies to local functions -- they can only be used after they are declared, thus the following is invalid:

1function blah()
2    print( a() )
3end
4 
5local function a()
6    return 5
7end
8 
9blah() -- a() will cause "attempt to call a nil value"

In addition, it lets you hide functions entirely:

01do
02    local function blah(x)
03        return x + math.random()
04    end
05 
06    function save(x)
07        return blah(x)
08    end
09end
10 
11print(save(5)) -- 5.432426812304
12print(blah(5)) -- attempt to call a nil value

According to Programming in Lua, the following two are equivalent:

1local function name()
2    --body
3end
4 
5local name; name = function()
6    -- body
7end
4
To be honest, I didn't know about the out-of-order execution thing myself. adark 5487 — 10y
Ad
Log in to vote
4
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
10 years ago

There is no difference between 'local' functions and 'normal' functions, actually.

First, a bit of clarification: Functions do not fire events, they listen to them. The ROBLOX engine itself fires them, passing in relevant information as arguments. Also, Function is invalid, as Lua is case-sensitive.

What's going on is a shortcut of Lua:

1function Name(params)
2    --end
3end
4 
5--Is the EXACT SAME as:
6 
7Name = function(params)
8    --end
9end

Functions are first-class values in Lua, meaning that you can treat them as any other kind of variable. If you are familiar with C, Lua functions are more accurately function pointers.

This is why you'll see code like this:

1loadstring(str)() --Where 'str' is a string of valid Lua code

The first set of parentheses calls loadstring, which returns a Lua function. The second set of parentheses calls that function.


As you probably know, the local keyword in Lua indicates the scope of a variable. If not, let me explain:

01var1 = true --Global variable. In many implementations, this would be shared across 'Scripts'. Not in ROBLOX, however.
02 
03local var2 = false --Local variable, to the script. Functionally identical to the above, since the 'scope' is the entire script. Is slightly faster to access.
04 
05do
06    var3 = "Red Fish" --Global variable. Even though it is declared inside of a code block, it is accessible outside of it.
07 
08    local var4 = "Blue fish" --Local variable. *Not* accessible outside of this code block.
09 
10    print(var1) --> true
11    print(var2) --> false
12    --Variables are always available in "child" blocks, like this one.
13end
14 
15print(var3) --> Red Fish
View all 30 lines...

When you make a function local, the same rules apply. Using top-level local variables in place of globals gives a considerable performance increase after a while, so that's why it's common to see them.


One last word on functions, and Tables as well:

Unlike other variables types, functions and Tables are, effectively, pointers. This is why you get something like this when you try to print them. When you pass a Table or function around as an argument to some function call, you are actually passing a reference to the Table/function. Any other variable type is copied into a function's 'upvalues', which are the parameters:

01local function RunThis(tableParam, functionParam, otherParam)
02    tableParam[27] = true
03    otherParam = otherParam .. "YOLOSWAGGY"
04 
05    print(tableParam)
06    print(functionParam)
07    print(otherParam)
08end
09 
10local str = "String"
11local tab = {"Test1", "Test3"}
12 
13print(str) --> String
14print(tab[27]) --> nil
15print(tab) --> table: XXXXXXXA
View all 24 lines...

tab and RunThis are pointers, to a Table and a function, respectively. RunThis() calls the function at the end of the pointer.

Notice, modifying the str upvalue passed into the RunThis call does not modify the external str variable. Modifying the Table's members, however, does modify the external Table. It is not possible (AFAIK) to modify the external function using just its upvalue.

A further note on upvalues: they act as local variables, following the rules above, so:

01local tab = {}
02local tab2 = {}
03 
04function RunThis(tab, X)
05    tab = {X = 25, Y = 17}
06 
07    X.X = 26
08    X.Y = 17
09    X = {}
10end
11 
12RunThis(tab, tab2)
13 
14print(tab.X) --> nil
15print(tab.Y) --> nil
16--The `tab` upvalue in the function *overrides* the higher-scoped `tab` declaration on line 1.
17 
18print(tab2.X) --> 26
19print(tab2.Y) --> 17
20--The same thing here. Even though we set X to an empty Table at the end of the function, that simply overrode the upvalue.

And, finally, reusing local variables:

In the above code, you'll notice that I did not write local X = {}. This is because X is already local. Since it was declared in the function definition as an upvalue (remember, parameters are upvalues), rewriting it in the 'global' scope simply reuses whatever scope the variable already had.

This is because variables in Lua do not have a specified Type. That is,

1local x = true
2x = "false"
3x = 261

Is all valid Lua. In a language like C, that kind of code would produce a compile error, as x is either a Boolean or a String or an Integer, and definitely not all three at once.

All three of those x declarations are local, because the initial declaration is. When a higher-scoped variable is overridden, the most recent scope is used:

01local x = 27
02 
03function RunThis()
04    x = 45 --Same var as on line 1. If this code were all wrapped in a code block, this would not be accessible outside of it.
05 
06    local x = 18 --New scope, to this function.
07 
08    x = "BOOLEAN" --Same scope as the line above, *not* the same as Line 1.
09end
10 
11RunThis()

If you've been paying attention thus far, you'll realize that you can declare functions inside of code blocks:

1function makeFunction(str)
2    local function func()
3        print("yolo" .. str)
4    end
5 
6    return func
7end
8 
9makeFunction("swag")() --> yoloswag

And as members of Tables:

01local tab = {}
02 
03tab.Func = function()
04    --code
05end
06 
07--Or:
08 
09function tab.Func2()
10    --code
11end

This second case is how you can make methods as opposed to functions:

01tab = {Applesauce = true}
02 
03function tab.func(t)
04    print(t.Applesauce)
05end
06 
07function tab:func2(appl) --Note the `:` here.
08    self.Applesauce = appl --"Method declaration" gives you a `self` parameter.
09end
10--This function is identical to:
11function tab.func2(self, appl)
12    self.Applesauce = appl
13end
14 
15--You can call these as either functions *or* methods:
View all 28 lines...
Log in to vote
-3
Answered by
vat21s 0
10 years ago

Local functions are more optimized, and should be used where possible.

0
Please have a Better description, I couldn't quite understand that. woodengop 1134 — 10y
0
Please view this article http://wiki.roblox.com/index.php?title=Performance, A locally referenced function is quicker and easier for Lua to access than a global scope one. vat21s 0 — 10y