local functions

i may sound incredibly stupid, but ive noticed a hell of a lot of people don’t localise there functions and i dont know why?

Hi @86lemonade68.

While we do like to encourage localizing functions (and other objects and variables) and to avoid globals, the reality is that new programmers can easily program themselves into a box where the only solution they see is to make a function global.  They haven’t learned how to forward declare functions and order does matter when referencing things.

Most programmers will go through various stages as they learn more and more about the language they are using and sometimes it comes from hard lessons learned from where globals have created issues or they have boxed themselves in.  As they mature, they learn to avoid the pitfalls.

We can encourage, teach and promote good code behavior, but we can’t enforce it.

Also sometimes a function may not look localized when it is.  A couple of examples:

local myfunction

myfunction = function(params)

end

This is an example of using Forward declaration but the “local myfunction” could be so far away, its hard to realize if it’s local or global (since of course if you forget the “local myfunction” it’s global).

The other instance is object method:

function myobject.myfunction()

end

Now my function is a  member of the table/object “myobject”.  Who knows at this point if myobject is local or global, but it inherits the scope of its parent “myobject”.

Rob

Hi @86lemonade68.

While we do like to encourage localizing functions (and other objects and variables) and to avoid globals, the reality is that new programmers can easily program themselves into a box where the only solution they see is to make a function global.  They haven’t learned how to forward declare functions and order does matter when referencing things.

Most programmers will go through various stages as they learn more and more about the language they are using and sometimes it comes from hard lessons learned from where globals have created issues or they have boxed themselves in.  As they mature, they learn to avoid the pitfalls.

We can encourage, teach and promote good code behavior, but we can’t enforce it.

Also sometimes a function may not look localized when it is.  A couple of examples:

local myfunction

myfunction = function(params)

end

This is an example of using Forward declaration but the “local myfunction” could be so far away, its hard to realize if it’s local or global (since of course if you forget the “local myfunction” it’s global).

The other instance is object method:

function myobject.myfunction()

end

Now my function is a  member of the table/object “myobject”.  Who knows at this point if myobject is local or global, but it inherits the scope of its parent “myobject”.

Rob