Global Variables in Lua Programming


Global variables in Lua are the variables that don’t need any type of declaration in them. We can simply define the name of the variable and assign any value we want to it, without having to use any keyword with it.

Having global variables makes certain programming cases possible, and it is also preferred if we want to create a variable that we want to use in multiple functions. In case we don’t use global variables, we might have to pass that variable to different functions where we want to use it, which is a bit more tedious.

Syntax

The syntax for declaring a global variable in Lua is pretty straightforward, just declare whatever name you want to use for your variable and assign a value to it.

<variable name> = <assigned value>

It should be noted that we cannot declare a global variable without assigning any value to it, as it is not something that Lua allows us to do.

Example

Consider the example shown below −

ans
print(ans)

In the above code sample, I am trying to declare a variable named ans and not assign anything to it. This will result in an error.

Output

input:2: syntax error near 'print'

Also, on the contrary, if I don’t create a variable and try printing it or accessing it in a function, then Lua won’t throw me an error, it will simply print "nil". It considers non-initialized variables only when you don’t explicitly create them without assigning them anything.

Example

Consider the example shown below −

print(a)

In the example above, I haven’t created a variable named a, but when I try to access it, then Lua will not throw an error.

Output

nil

Now, let’s look at a bit more extensive example of global variables in Lua, where we consider a few more cases that we need to handle while declaring and making use of the global variables.

Example


print(ans)

i = 10
print(i)

_x = nil

print(_x)

_X = "mukul"
print(_X)

Output

nil
10
nil
mukul

Updated on: 01-Dec-2021

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements