• Lua: Types and Values (Variables)

    6 Jul 2016
    Karthik Padmanabhan

    Lua is a dynamically typed language. There are no type definitions in the language; each value carries its own type.

    There are eight basic types in Lua: nil, boolean, number, string, userdata, function, thread, and table. The type function gives the type name of a given value:

    	print(type("Hello world"))  --> string
    	print(type(10.4*3))         --> number
    	print(type(print))          --> function
    	print(type(type))           --> function
    	print(type(true))           --> boolean
    	print(type(nil))            --> nil
    	print(type(type(X)))        --> string

    The last example will result in “string” no matter the value of X, because the result of type is always a string.
    Variables have no predefined types; any variable may contain values of any type:

        print(type(a))   --> nil   (`a' is not initialized)
        a = 10
        print(type(a))   --> number
        a = "a string!!"
        print(type(a))   --> string
        a = print        -- yes, this is valid!
        a(type(a))       --> function

    Notice the last two lines: Functions are first-class values in Lua; so, we can manipulate them like any other value.
    Usually, when you use a single variable for different types, the result is messy code. However, sometimes the judicious use of this facility is helpful, for instance in the use of nil to differentiate a normal return value from an exceptional condition.


    Nil is a type with a single value, nil, whose main property is to be different from any other value. As we have seen, a global variable has a nil value by default, before a first assignment, and you can assign nil to a global variable to delete it. Lua uses nil as a kind of non-value, to represent the absence of a useful value.


    The boolean type has two values, false and true, which represent the traditional boolean values. However, they do not hold a monopoly of condition values: In Lua, any value may represent a condition. Conditionals (such as the ones in control structures) consider false and nil as false and anything else as true. Beware that, unlike some other scripting languages, Lua considers both zero and the empty string as true in conditional tests.


    The number type represents real (double-precision floating-point) numbers. Lua has no integer type, as it does not need it. There is a widespread misconception about floating-point arithmetic errors and some people fear that even a simple increment can go weird with floating-point numbers. The fact is that, when you use a double to represent an integer, there is no rounding error at all (unless the number is greater than 100,000,000,000,000). Specifically, a Lua number can represent any long integer without rounding problems. Moreover, most modern CPUs do floating-point arithmetic as fast as (or even faster than) integer arithmetic.

    It is easy to compile Lua so that it uses another type for numbers, such as longs or single-precision floats. This is particularly useful for platforms without hardware support for floating point. See the distribution for detailed instructions.

    We can write numeric constants with an optional decimal part, plus an optional decimal exponent.


    Strings have the usual meaning: a sequence of characters. Lua is eight-bit clean and so strings may contain characters with any numeric value, including embedded zeros. That means that you can store any binary data into a string. Strings in Lua are immutable values. You cannot change a character inside a string, as you may in C; instead, you create a new string with the desired modifications.


    The table type implements associative arrays. An associative array is an array that can be indexed not only with numbers, but also with strings or any other value of the language, except nil. Moreover, tables have no fixed size; you can add as many elements as you want to a table dynamically. Tables are the main (in fact, the only) data structuring mechanism in Lua, and a powerful one. We use tables to represent ordinary arrays, symbol tables, sets, records, queues, and other data structures, in a simple, uniform, and efficient way. Lua uses tables to represent packages as well. When we write, we mean “the read entry from the io package”. For Lua, that means “index the table io using the string “read” as the key”.

    Tables in Lua are neither values nor variables; they are objects. If you are familiar with arrays in Java or Scheme, then you have a fair idea of what we mean. However, if your idea of an array comes from C or Pascal, you have to open your mind a bit. You may think of a table as a dynamically allocated object; your program only manipulates references (or pointers) to them. There are no hidden copies or creation of new tables behind the scenes. Moreover, you do not have to declare a table in Lua; in fact, there is no way to declare one. You create tables by means of a constructor expression, which in its simplest form is written as {}.


    Functions are first-class values in Lua. That means that functions can be stored in variables, passed as arguments to other functions, and returned as results. Such facilities give great flexibility to the language: A program may redefine a function to add new functionality, or simply erase a function to create a secure environment when running a piece of untrusted code (such as code received through a network). Moreover, Lua offers good support for functional programming, including nested functions with proper lexical scoping; just wait. Finally, first-class functions play a key role in Lua’s object-oriented facilities.

    Lua can call functions written in Lua and functions written in C. All the standard library in Lua is written in C. It comprises functions for string manipulation, table manipulation, I/O, access to basic operating system facilities, mathematical functions, and debugging. Application programs may define other functions in C.

    Userdata and Threads

    The userdata type allows arbitrary C data to be stored in Lua variables. It has no predefined operations in Lua, except assignment and equality test. Userdata are used to represent new types created by an application program or a library written in C; for instance, the standard I/O library uses them to represent files. We will discuss more about userdata later, when we get to the C API.

    Example programs

    --Re-using variables
    print("Value of a: ",a)
    print("Value of a: ",a)
    print("Value of a: ",a)
    print("Value of a: ",a)
    print("Any variable in Lua can be of any data type.")
    --Using literals
    page= [[An HTML Page
    --Tables in lua
    --Creating tables
    a = {}
    k = "x"
    a[k] = 10
    a[20] = "great"
    k = 20
    a["x"] = a["x"] + 1
    --Refer tables
    a = {}
    a["x"] = 10
    b = a
    b["x"] = 20
    a = nil
    --b = nil
    Continue Reading
  • Lua: Writing simple method using return statement

    4 Jul 2016
    Karthik Padmanabhan

    Today, we will learn and use methods and return statement in our Program. Programming in Lua is more like Programming in C. If you are familiar with C then Lua is pretty easy to learn.

    Program code:

    function IsEven (n)
        if n%2 == 0 then
            return "Even"
            return "Odd"
    print("Enter a Number: ")"*number")
    print("Number ",a,"is ",IsEven(a))

    In the above program, we have created a method IsEven(...), which takes a number as input and identifies if it is Even or Odd and returns a string which is printed as output to the console. Also, if you notice, we have used, this allows us to take an input from the user and read it using system io stream and assigns it to the variable a for us to make use of.

    The next program that we will learn will contain more code and will be a little more extensive. Stay tuned for that.

    Continue Reading
  • Lua: Hello World!

    3 Jul 2016
    Karthik Padmanabhan

    So, today we are going to learn our first Lua Program. Yes! You have guessed it correctly. It’s the “Hello World” program.

    We have already installed the required Interpreter for Compiling and Executing Lua code on out machine. (Refer: Programming in Lua)

    1. Open Visual Studio Code and create a new file.
    2. Lua uses the print(...) to output text to the console. So, we are gonna write print("Hello World") This will output a string “Hello World” onto the console.
    3. Save the program with the filename extension as .lua to your desired folder path.
    4. Open a command window in the folder path and type lua <filename.lua> and hit return to compile and execute the program.
    5. You have successfully written the first Lua Program.

    You will see the following result in your command windows.


    Continue Reading
  • Programming in Lua

    2 Jul 2016
    Karthik Padmanabhan

    Hello! For a long time now, I wanted to learn Lua. But, have never had time to get started with learning it.

    Now, I am very eager to learn it, because I have time to learn and experiment with code. Also, a lot of my known developers have been telling me that its good to learn Lua since it is more Robust and very helpful in Game Development. Hence, I am starting this series where I will share my knowledge as I learn Lua.

    I am going to use the pre-compiled LuaForWindows as my Lua Binary. Also, I am using Visual Studio Code as my IDE to write code in Lua.

    I will be following the “Programming in Lua by Roberto Ierusalimschy” and “The.Lua.Tutorial” as my guide to learning Lua.


    Binaries: (Windows) LuaForWidnows , (MacOS) Rudix , (Linux) LuaInterpreter

    IDE: Visual Studio Code

    Continue Reading