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

What's the difference between these two function types?

Asked by 5 years ago

One way to define a function is:

local function This(x)
    print(x)
end

Another way is:

local This = function(x)
    print(x)
end

Is there a difference between the two and is there a performance difference between them?

0
quick answer: local function a() end is syntax sugar for local a; a = function end. since `a` is then defined it can be called recursively. EpicMetatableMoment 1444 — 5y

1 answer

Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

1. You really don't need to be worrying about "lag and performance." At this point you're misusing these terms.

2. There are no different "types" of functions in Lua.

Functions are their own data type, kind of like how strings and tables and so on are their own data type.

The only differences of course would be how they're being used.

Your first example is syntactic sugar (a nicer way to write something else) for

lua local This This = function(x) print(x) end

This makes This (no pun intended) an upvalue (external local variable) inside the function scope. This also allows for recursion. Your second example would not allow recursion.

Let me use a famous example of recursion

```lua local function fact(num) if (rawequal(num, 0)) then return 1; --// 0! = 1 end return num*fact(num - 1); end

print(fact(5)); --> 120 ```

But if we wrote it in your second example's format:

```lua local fact = function(num) if (rawequal(num, 0)) then return 1; --// 0! = 1 end return num*fact(num - 1); end

print(fact(5)); --> attempt to call a nil value (global 'fact') ```

There is an "attempt to call a nil value" error.

1
ok this thing is glitched brb don't -1 User#24403 69 — 5y
1
apparently i can't answer on a ipad with a physical keyboard so here's a link to my explanation https://pastebin.com/jzB1nbm6 User#24403 69 — 5y
1
what an amazing post EpicMetatableMoment 1444 — 5y
1
best post ever lets upvote it hiimgoodpack 2009 — 5y
1
lol DeceptiveCaster 3761 — 5y
Ad

Answer this question