Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Lua default to global variables?

Tags:

lua

My favourite language these days is Lua. I have only one issue with it, why on earth is its default behaviour that variables in functions are global? In the similar language Icon there is a keyword "global" that is used when one really wants to use a global instead of the natural behaviour to default to local (I was bitten by this again five minutes ago). I would feel better about this if somebody could tell me the rational behind it (like the scoping difficulties that I know cause the absence of a "continue" keyword in Lua).

like image 396
AndersH Avatar asked Oct 07 '10 11:10

AndersH


People also ask

Are Lua variables global?

In Lua, though we don't have variable data types, we have three types based on the scope of the variable. Global variables − All variables are considered global unless explicitly declared as a local.

Are Lua functions global?

Because Lua keeps its global variables in a regular table, we can use metatables to change its behavior when accessing global variables.

How do you avoid global variables?

The simplest way to avoid globals all together is to simply pass your variables using function arguments. As you can see, the $productData array from the controller (via HTTP request) goes through different layer: The controller receives the HTTP request. The parameters are passed to the model.


1 Answers

See Why aren't variables locally scoped by default? in the Lua uFAQ.

It certainly feels easy to only explicitly declare globals when they are in a local context. The short answer is that Lua is not Python, but there are actually good reasons why lexically-scoped local variables have to be explicitly declared. See the wiki page.

like image 170
lhf Avatar answered Sep 23 '22 01:09

lhf