Wednesday, 31 August 2016

today i got the call for installation of tersterm, baiscally teraterm is used to view the output from the board. when we build a binary on the board and then it is flashed. After flashing, it generates an output which we want to see. 

the output is viewed just like it is viewed when we run a simple c or java program and then it is run.

On teraterm we select a proper COM port on which our MCU is recognised. after recognition, serial port settings are changed according to given code. all the code according to its setting work on different baud rates or parity or any other option.

So today I mademy code run and just printed a HELLO after flashing just to check code works fine and I get to know some settings.

Tuesday, 30 August 2016

with stm cubemx, we can generate an initial code which forms the basic outline for writing the advance part of the code.

in this software, we select the type of board on which we have to work, select the name of that particular board and some options inside which generate the code.


STM32CubeMX is part of STMicroelectronics STMCube™ original initiative to ease developers life by reducing development efforts, time and cost. STM32Cube covers STM32 portfolio.
STM32Cube includes the STM32CubeMX which is a graphical software configuration tool that allows generating C initialization code using graphical wizards.
It also embeds a comprehensive software platform, delivered per series (such as STM32CubeF4 for STM32F4 series). This platform includes the STM32Cube HAL (an STM32 abstraction layer embedded software, ensuring maximized portability across STM32 portfolio), plus a consistent set of middleware components (RTOS, USB, TCP/IP and graphics). All embedded software utilities come with a full set of examples.
STM32CubeMX is a graphical tool that allows configuring STM32 microcontrollers very easily and generating the corresponding initialization C code through a step-by-step process.
Step one consists in selecting the STMicroelectronics STM32 microcontroller that matches the required set of peripherals.
The user must then configure each required embedded software thanks to a pinout-conflict solver, a clock-tree setting helper, a power-consumption calculator, and an utility performing MCU peripheral configuration (GPIO, USART, ..) and middleware stacks (USB, TCP/IP, ...).
Finally, the user launches the generation of the initialization C code based on the selected configuration. This code is ready to be used within several development environments. The user code is kept at the next code generation.
Key Features
  • Intuitive STM32 microcontroller selection
  • Microcontroller graphical configuration:
    • Pinout with automatic conflict resolution
    • Clock tree with dynamic validation of configuration
    • Peripherals and middleware functional modes and initialization with dynamic validation of parameter constraints
    • Power sequence with estimate of consumption results
  • C code project generation covering STM32 microcontroller initialization compliant with IAR™, Keil™ and GCC compilers.

it releases code which could be used for a particular board only.

Monday, 29 August 2016


I put a request on friday to install system work bench, today I got the call for installation of the software. There is another software which sir asked me to install.

Terterm, it is a hyperterminal as windows 7 and vista do not come with any..
Teragerm is opensource software terminal emulator that works with windows 7 and vista.

Again I requested them to install this into my machine.

System workbench was installed on my machine. Sir asked me to download all the lua source code which  is available on github.
I put a request on friday to install system work bench, today I got the call for installation of the software. There is another software which sir asked me to install.

Terterm, it is a hyperterminal as windows 7 and vista do not come with any..
Teragerm is opensource software terminal emulator that works with windows 7 and vista.

Again I requested them to install this into my machine.

System workbench was installed on my machine. Sir asked me to download all the lua source code which  is available on github.

Friday, 26 August 2016

today I  was asked to download system workbench which is eclipse based iDE to interact with the board. it is alsoan open source technology which can be easily downloaded from ac6 website by registering. It has 2 ways to download either with the installer or through eclipse.

In the installer, we get ST link driver in it which is used to link and recognise the board.

a request was made on my part to the manager as I didnt have admin rights.

Thursday, 25 August 2016

Today I did a complete study for UART.

A UART (Universal Asynchronous Receiver/Transmitter) is the microchip with programming that controls a computer's interface to its attached serial devices. Specifically, it provides the computer with the RS-232C Data Terminal Equipment ( DTE ) interface so that it can "talk" to and exchange data with modems and other serial devices. As part of this interface, the UART also:
  • Converts the bytes it receives from the computer along parallel circuits into a single serial bit stream for outbound transmission
  • On inbound transmission, converts the serial bit stream into the bytes that the computer handles
  • Adds a parity bit (if it's been selected) on outbound transmissions and checks the parity of incoming bytes (if selected) and discards the parity bit
  • Adds start and stop delineators on outbound and strips them from inbound transmissions
  • Handles interrupt s from the keyboard and mouse (which are serial devices with special port s)
  • May handle other kinds of interrupt and device management that require coordinating the computer's speed of operation with device speeds
More advanced UARTs provide some amount of buffering of data so that the computer and serial devices data streams remain coordinated. The most recent UART, the 16550, has a 16-byte buffer that can get filled before the computer's processor needs to handle the data. The original UART was the 8250. If you purchase an internal modem today, it probably includes a 16550 UART (although you should ask when you buy it). According to modem manufacturer US Robotics, external modems do not include a UART. If you have an older computer, you may want to add an internal 16550 to get the most out of your external modem.

Tuesday, 23 August 2016

today I was given a board stm 32 NUCLEO-F302R8 and was asked to study about it. on internet, after some searching I got a documentation which was on this board.
So here are some details: Targeted MCU STM32F302RT6
Te purple mark indicates main stream board.

the communication between computer and the mcu or between two mcus is through UART i.e universal asynchronous reciever/transmitter.

there are 2 pins for data transfer

it sends or recieves data in form of chunks or packets(transmission characters)

Monday, 22 August 2016

Memory structure in C


Memory Layout of C Programs


A typical memory representation of C program consists of following sections.
1. Text segment
2. Initialized data segment
3. Uninitialized data segment
4. Stack
5. Heap

A typical memory layout of a running process
1. Text Segment:
A text segment , also known as a code segment or simply as text, is one of the sections of a program in an object file or in memory, which contains executable instructions.
As a memory region, a text segment may be placed below the heap or stack in order to prevent heaps and stack overflows from overwriting it.
Usually, the text segment is sharable so that only a single copy needs to be in memory for frequently executed programs, such as text editors, the C compiler, the shells, and so on. Also, the text segment is often read-only, to prevent a program from accidentally modifying its instructions.
2. Initialized Data Segment:
Initialized data segment, usually called simply the Data Segment. A data segment is a portion of virtual address space of a program, which contains the global variables and static variables that are initialized by the programmer.
Note that, data segment is not read-only, since the values of the variables can be altered at run time.
This segment can be further classified into initialized read-only area and initialized read-write area.
For instance the global string defined by char s[] = “hello world” in C and a C statement like int debug=1 outside the main (i.e. global) would be stored in initialized read-write area. And a global C statement like const char* string = “hello world” makes the string literal “hello world” to be stored in initialized read-only area and the character pointer variable string in initialized read-write area.
Ex: static int i = 10 will be stored in data segment and global int i = 10 will also be stored in data segment
3. Uninitialized Data Segment:
Uninitialized data segment, often called the “bss” segment, named after an ancient assembler operator that stood for “block started by symbol.” Data in this segment is initialized by the kernel to arithmetic 0 before the program starts executing
uninitialized data starts at the end of the data segment and contains all global variables and static variables that are initialized to zero or do not have explicit initialization in source code.
For instance a variable declared static int i; would be contained in the BSS segment.
For instance a global variable declared int j; would be contained in the BSS segment.
4. Stack:
The stack area traditionally adjoined the heap area and grew the opposite direction; when the stack pointer met the heap pointer, free memory was exhausted. (With modern large address spaces and virtual memory techniques they may be placed almost anywhere, but they still typically grow opposite directions.)
The stack area contains the program stack, a LIFO structure, typically located in the higher parts of memory. On the standard PC x86 computer architecture it grows toward address zero; on some other architectures it grows the opposite direction. A “stack pointer” register tracks the top of the stack; it is adjusted each time a value is “pushed” onto the stack. The set of values pushed for one function call is termed a “stack frame”; A stack frame consists at minimum of a return address.
Stack, where automatic variables are stored, along with information that is saved each time a function is called. Each time a function is called, the address of where to return to and certain information about the caller’s environment, such as some of the machine registers, are saved on the stack. The newly called function then allocates room on the stack for its automatic and temporary variables. This is how recursive functions in C can work. Each time a recursive function calls itself, a new stack frame is used, so one set of variables doesn’t interfere with the variables from another instance of the function.
5. Heap:
Heap is the segment where dynamic memory allocation usually takes place.
The heap area begins at the end of the BSS segment and grows to larger addresses from there.The Heap area is managed by malloc, realloc, and free, which may use the brk and sbrk system calls to adjust its size (note that the use of brk/sbrk and a single “heap area” is not required to fulfill the contract of malloc/realloc/free; they may also be implemented using mmap to reserve potentially non-contiguous regions of virtual memory into the process’ virtual address space). The Heap area is shared by all shared libraries and dynamically loaded modules in a process.

Friday, 19 August 2016

There are some platform specific files for example;
BUILD XMODEM
BUILD SHELL
BUILD ROMFS
BUILD MMCFS
BUILD TERM
BUILD UIP
etc.
all of which have different functionalities and are used in elua project for the stm 32 board.

these were the files which are to be inculcatred in my study.

Wednesday, 17 August 2016

There is a project which is called eLUA i.e Lua for embedded systems.It is somewhat sort of which we ought to do with Lua. The only difference being eLua works on a specific board and we want to do something general i.e which is not for specific board but for all.

So I did a study for elua source code as to what changes they have made in Lua main source code.

There are some generic modules like
adc
bit
cpu
12c..

today I did a study on this.

Tuesday, 16 August 2016

After studying the code, i understood that pointers have a great role in writing that code and if i have to port it on to the board i.e STM 32 then I have to study about dynamic memory allocation, in normal pointers. So today I started with studying dynamic memory allocation in C.


pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration is −
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Take a look at some of the valid pointer declarations −The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.

How to Use Pointers?

There are a few important operations, which we will do with the help of pointers very frequently. (a) We define a pointer variable, (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. The following example makes use of these operations −

Thursday, 11 August 2016

Next task was to download lua source code which is readily available on internet as it is an open-source technology.I downloaded it and differntiated all the files into categories. It had .c and .h files.
for example
All the code was to be studied, not in whole but for having a basic understanding of what is in the files and what work they do.

Tuesday, 9 August 2016

Now came the main part of studying the API for writing the code. In the book for programming in LUA, a first example was given, which was a simple example for combination of lua with C.

#include <stdio.h>
    #include <string.h>
    #include <lua.h>
    #include <lauxlib.h>
    #include <lualib.h>
    
    int main (void) {
      char buff[256];
      int error;
      lua_State *L = lua_open();   /* opens Lua */
      luaopen_base(L);             /* opens the basic library */
      luaopen_table(L);            /* opens the table library */
      luaopen_io(L);               /* opens the I/O library */
      luaopen_string(L);           /* opens the string lib. */
      luaopen_math(L);             /* opens the math lib. */
    
      while (fgets(buff, sizeof(buff), stdin) != NULL) {
        error = luaL_loadbuffer(L, buff, strlen(buff), "line") ||
                lua_pcall(L, 0, 0, 0);
        if (error) {
          fprintf(stderr, "%s", lua_tostring(L, -1));
          lua_pop(L, 1);  /* pop error message from the stack */
        }
      }
    
      lua_close(L);
      return 0; 
    } 

In this example, C's file handling is combined with lua stack. If there is no error, then the stack is pushed with the code and then popped toget printed output. 

This is just a brief working of this API.

Monday, 8 August 2016

Lua with c

the main motive of studying LUA was to use it with C, so today starting with LUCA i.e lua with c. Lua has a separate API to work with C easily.

A basic introduction to LUA API:

Lua is an embedded language. That means that Lua is not a stand-alone package, but a library that can be linked with other applications so as to incorporate Lua facilities into these applications.
You may be wondering: If Lua is not a stand-alone program, how come we have been using Lua stand alone through the whole book? The solution to this puzzle is the Lua interpreter (the executable lua). This interpreter is a tiny application (with less than five hundred lines of code) that uses the Lua library to implement the stand-alone interpreter. This program handles the interface with the user, taking her files and strings to feed them to the Lua library, which does the bulk of the work (such as actually running Lua code).
This ability to be used as a library to extend an application is what makes Lua an extension language. At the same time, a program that uses Lua can register new functions in the Lua environment; such functions are implemented in C (or another language) and can add facilities that cannot be written directly in Lua. This is what makes Lua an extensible language.
These two views of Lua (as an extension language and as an extensible language) correspond to two kinds of interaction between C and Lua. In the first kind, C has the control and Lua is the library. The C code in this kind of interaction is what we call application code. In the second kind, Lua has the control and C is the library. Here, the C code is called library code. Both application code and library code use the same API to communicate with Lua, the so called C API.
The C API is the set of functions that allow C code to interact with Lua. It comprises functions to read and write Lua global variables, to call Lua functions, to run pieces of Lua code, to register C functions so that they can later be called by Lua code, and so on. (Throughout this text, the term "function" actually means "function or macro". The API implements several facilities as macros.)
The C API follows the C modus operandi, which is quite different from Lua. When programming in C, we must care about type checking (and type errors), error recovery, memory-allocation errors, and several other sources of complexity. Most functions in the API do not check the correctness of their arguments; it is your responsibility to make sure that the arguments are valid before calling a function. If you make mistakes, you can get a "segmentation fault" error or something similar, instead of a well-behaved error message. Moreover, the API emphasizes flexibility and simplicity, sometimes at the cost of ease of use. Common tasks may involve several API calls. This may be boring, but it gives you full control over all details, such as error handling, buffer sizes, and the like.
As its title says, the goal of this chapter is to give an overview of what is involved when you use Lua from C. Do not bother understanding all the details of what is going on now. Later we will fill in the details. Nevertheless, do not forget that you can find more details about specific functions in the Lua reference manual. Moreover, you can find several examples of the use of the API in the Lua distribution itself. The Lua stand-alone interpreter (lua.c) provides examples of application code, while the standard libraries (lmathlib.clstrlib.c, etc.) provide examples of library code.
From now on, we are wearing a C programmers' hat. When we talk about "you", we mean you when programming in C, or you impersonated by the C code you write.

Friday, 5 August 2016


The power of a raw Lua interpreter to manipulate strings is quite limited. A program can create string literals and concatenate them. But it cannot extract a substring, check its size, or examine its contents. The full power to manipulate strings in Lua comes from its string library.
Some functions in the string library are quite simple: string.len(s) returns the length of a string sstring.rep(s, n) returns the string srepeated n times. You can create a string with 1M bytes (for tests, for instance) with string.rep("a", 2^20)string.lower(s) returns a copy of s with the upper-case letters converted to lower case; all other characters in the string are not changed (string.upper converts to upper case). As a typical use, if you want to sort an array of strings regardless of case, you may write something like
    table.sort(a, function (a, b)
      return string.lower(a) < string.lower(b)
    end)
Both string.upper and string.lower follow the current locale. Therefore, if you work with the European Latin-1 locale, the expression
    string.upper("ação")
results in "AÇÃO".
The call string.sub(s,i,j) extracts a piece of the string s, from the i-th to the j-th character inclusive. In Lua, the first character of a string has index 1. You can also use negative indices, which count from the end of the string: The index -1 refers to the last character in a string, -2 to the previous one, and so on. Therefore, the call string.sub(s, 1, j) gets a prefix of the string s with length jstring.sub(s, j, -1) gets a suffix of the string, starting at the j-th character (if you do not provide a third argument, it defaults to -1, so we could write the last call as string.sub(s, j)); and string.sub(s, 2, -2) returns a copy of the string s with the first and last characters removed:
    s = "[in brackets]"
    print(string.sub(s, 2, -2))   -->  in brackets
Remember that strings in Lua are immutable. The string.sub function, like any other function in Lua, does not change the value of a string, but returns a new string. A common mistake is to write something like
    string.sub(s, 2, -2)
and to assume that the value of s will be modified. If you want to modify the value of a variable, you must assign the new value to the variable:
    s = string.sub(s, 2, -2)
The string.char and string.byte functions convert between characters and their internal numeric representations. The function string.char gets zero or more integers, converts each one to a character, and returns a string concatenating all those characters. The function string.byte(s, i) returns the internal numeric representation of the i-th character of the string s; the second argument is optional, so that a call string.byte(s) returns the internal numeric representation of the first (or single) character of s. In the following examples, we assume that characters are represented in ASCII:
    print(string.char(97))                    -->  a
    i = 99; print(string.char(i, i+1, i+2))   -->  cde
    print(string.byte("abc"))                 -->  97
    print(string.byte("abc", 2))              -->  98
    print(string.byte("abc", -1))             -->  99
In the last line, we used a negative index to access the last character of the string.
The function string.format is a powerful tool when formatting strings, typically for output. It returns a formatted version of its variable number of arguments following the description given by its first argument, the so-called format string. The format string has rules similar to those of the printf function of standard C: It is composed of regular text and directives, which control where and how each argument must be placed in the formatted string. A simple directive is the character `%´ plus a letter that tells how to format the argument: `d´ for a decimal number, `x´ for hexadecimal, `o´ for octal, `f´ for a floating-point number, `s´ for strings, plus other variants. Between the `%´ and the letter, a directive can include other options, which control the details of the format, such as the number of decimal digits of a floating-point number:
    print(string.format("pi = %.4f", PI))     --> pi = 3.1416
    d = 5; m = 11; y = 1990
    print(string.format("%02d/%02d/%04d", d, m, y))
      --> 05/11/1990
    tag, title = "h1", "a title"
    print(string.format("<%s>%s</%s>", tag, title, tag))
      --> <h1>a title</h1>
In the first example, the %.4f means a floating-point number with four digits after the decimal point. In the second example, the %02dmeans a decimal number (`d´), with at least two digits and zero padding; the directive %2d, without the zero, would use blanks for padding. For a complete description of those directives, see the Lua reference manual. Or, better yet, see a C manual, as Lua calls the standard C libraries to do the hard work here.

object oriented programing in lua

A table in Lua is an object in more than one sense. Like objects, tables have a state. Like objects, tables have an identity (a selfness) that is independent of their values; specifically, two objects (tables) with the same value are different objects, whereas an object can have different values at different times, but it is always the same object. Like objects, tables have a life cycle that is independent of who created them or where they were created.
Account = {balance = 0}
function Account.withdraw (v)
Account.balance = Account.balance - v
end
Account.withdraw(100.00)
a = Account; Account = nil
a.withdraw(100.00) -- ERROR!
function Account.withdraw (self, v)
self.balance = self.balance - v
end
a1 = Account; Account = nil
...
a1.withdraw(a1, 100.00) -- OK
a2 = {balance=0, withdraw = Account.withdraw}
...
a2.withdraw(a2, 260.00)
function Account:withdraw (v)
self.balance = self.balance - v
end
a:withdraw(100.00)
Account = { balance=0,
withdraw = function (self, v)
self.balance = self.balance - v
end
}
function Account:deposit (v)
self.balance = self.balance + v
end
Account.deposit(Account, 200.00)
Account:withdraw(100.00)
Objects have their own operations. Tables also can have operations:
This definition creates a new function and stores it in field withdraw of the Account object. Then, we can call it as
This kind of function is almost what we call a method. However, the use of the global name Account inside the function is a bad programming practice. First, this function will work only for this particular object. Second, even for this particular object the function will work only as long as the object is stored in that particular global variable; if we change the name of this object, withdraw does not work any more:
Such behavior violates the previous principle that objects have independent life cycles.
A more flexible approach is to operate on the receiver of the operation. For that, we would have to define our method with an extra parameter, which tells the method on which object it has to operate. This parameter usually has the name self or this:
Now, when we call the method we have to specify on which object it has to operate:
With the use of a self parameter, we can use the same method for many objects:
This use of a self parameter is a central point in any object-oriented language. Most OO languages have this mechanism partly hidden from the programmer, so that she does not have to declare this parameter (although she still can use the name self or this inside a method). Lua can also hide this parameter, using the colon operator. We can rewrite the previous method definition as
and the method call as
The effect of the colon is to add an extra hidden parameter in a method definition and to add an extra argument in a method call. The colon is only a syntactic facility, although a convenient one; there is nothing really new here. We can define a function with the dot syntax and call it with the colon syntax, or vice-versa, as long as we handle the extra parameter correctly:
Now our objects have an identity, a state, and operations over this state. They still lack a class system, inheritance, and privacy. Let us tackle the first problem: How can we create several objects with similar behavior? Specifically, how can we create several accounts?

Wednesday, 3 August 2016

tables in lua

Tables are the most important part in lua..all the data structures are based on tables.


Tables in Lua are not a data structure; they are the data structure. All structures that other languages offer---arrays, records, lists, queues, sets---are represented with tables in Lua. More to the point, tables implement all these structures efficiently.
In traditional languages, such as C and Pascal, we implement most data structures with arrays and lists (where lists = records + pointers). Although we can implement arrays and lists using Lua tables (and sometimes we do that), tables are more powerful than arrays and lists; many algorithms are simplified to the point of triviality with the use of tables. For instance, you seldom write a search in Lua, because tables offer direct access to any type.
It takes a while to learn how to use tables efficiently. Here, we will show how you can implement typical data structures with tables and will provide some examples of their use. We will start with arrays and lists, not because we need them for the other structures, but because most programmers are already familiar with them. We have already seen the basics of this material in our chapters about the language, but I will repeat it here for completeness.

We implement arrays in Lua simply by indexing tables with integers. Therefore, arrays do not have a fixed size, but grow as we need. Usually, when we initialize the array we define its size indirectly. For instance, after the following code
    a = {}    -- new array
    for i=1, 1000 do
      a[i] = 0
    end
any attempt to access a field outside the range 1-1000 will return nil, instead of zero.
You can start an array at index 0, 1, or any other value:
    -- creates an array with indices from -5 to 5
    a = {}
    for i=-5, 5 do
      a[i] = 0
    end
However, it is customary in Lua to start arrays with index 1. The Lua libraries adhere to this convention; so, if your arrays also start with 1, you will be able to use their functions directly.
We can use constructors to create and initialize arrays in a single expression:
    squares = {1, 4, 9, 16, 25, 36, 49, 64, 81}
Such constructors can be as large as you need (well, up to a few million elements).

Linked Lists

Because tables are dynamic entities, it is easy to implement linked lists in Lua. Each node is represented by a table and links are simply table fields that contain references to other tables. For instance, to implement a basic list, where each node has two fields, next and value, we need a variable to be the list root:
    list = nil
To insert an element at the beginning of the list, with a value v, we do
    list = {next = list, value = v}
To traverse the list, we write:
    local l = list
    while l do
      print(l.value)
      l = l.next
    end
Other kinds of lists, such as double-linked lists or circular lists, are also implemented easily. However, you seldom need those structures in Lua, because usually there is a simpler way to represent your data without using lists. For instance, we can represent a stack with an (unbounded) array, with a field n pointing to the top.

Monday, 1 August 2016

continuing with LUA..

Functions are the main mechanism for abstraction of statements and expressions in Lua. Functions can both carry out a specific task (what is sometimes called procedure or subroutine in other languages) or compute and return values. In the first case, we use a function call as a statement; in the second case, we use it as an expression:
    print(8*9, 9/8)
    a = math.sin(3) + math.cos(10)
    print(os.date())
In both cases, we write a list of arguments enclosed in parentheses. If the function call has no arguments, we must write an empty list () to indicate the call. There is a special case to this rule: If the function has one single argument and this argument is either a literal string or a table constructor, then the parentheses are optional:
    print "Hello World"     <-->     print("Hello World")
    dofile 'a.lua'          <-->     dofile ('a.lua')
    print [[a multi-line    <-->     print([[a multi-line
     message]]                        message]])
    f{x=10, y=20}           <-->     f({x=10, y=20})
    type{}                  <-->     type({})
Lua also offers a special syntax for object-oriented calls, the colon operator. An expression like o:foo(x) is just another way to write o.foo(o, x), that is, to call o.foo adding o as a first extra argument. In Chapter 16 we will discuss such calls (and object-oriented programming) in more detail.
Functions used by a Lua program can be defined both in Lua and in C (or in any other language used by the host application). For instance, all library functions are written in C; but this fact has no relevance to Lua programmers. When calling a function, there is no difference between functions defined in Lua and functions defined in C.
As we have seen in other examples, a function definition has a conventional syntax; for instance
    -- add all elements of array `a'
    function add (a)
      local sum = 0
      for i,v in ipairs(a) do
        sum = sum + v
      end
      return sum
    end
In that syntax, a function definition has a name (add, in the previous example), a list of parameters, and a body, which is a list of statements.
Parameters work exactly as local variables, initialized with the actual arguments given in the function call. You can call a function with a number of arguments different from its number of parameters. Lua adjusts the number of arguments to the number of parameters, as it does in a multiple assignment: Extra arguments are thrown away; extra parameters get nil. For instance, if we have a function like
    function f(a, b) return a or b end
we will have the following mapping from arguments to parameters:
    CALL             PARAMETERS
       
    f(3)             a=3, b=nil
    f(3, 4)          a=3, b=4
    f(3, 4, 5)       a=3, b=4   (5 is discarded)
Although this behavior can lead to programming errors (easily spotted at run time), it is also useful, especially for default arguments. For instance, consider the following function, to increment a global counter.
    function incCount (n)
      n = n or 1
      count = count + n
    end
This function has 1 as its default argument; that is, the call incCount(), without arguments, increments count by one. When you call incCount(), Lua first initializes n with nil; the or results in its second operand; and as a result Lua assigns a default 1 to n.

5.3 – Named Arguments

The parameter passing mechanism in Lua is positional: When we call a function, arguments match parameters by their positions. The first argument gives the value to the first parameter, and so on. Sometimes, however, it is useful to specify the arguments by name. To illustrate this point, let us consider the function rename (from the os library), which renames a file. Quite often, we forget which name comes first, the new or the old; therefore, we may want to redefine this function to receive its two arguments by name:
    -- invalid code
    rename(old="temp.lua", new="temp1.lua")
Lua has no direct support for that syntax, but we can have the same final effect, with a small syntax change. The idea here is to pack all arguments into a table and use that table as the only argument to the function. The special syntax that Lua provides for function calls, with just one table constructor as argument, helps the trick:
    rename{old="temp.lua", new="temp1.lua"}
Accordingly, we define rename with only one parameter and get the actual arguments from this parameter:
    function rename (arg)
      return os.rename(arg.old, arg.new)
    end
This style of parameter passing is especially helpful when the function has many parameters, and most of them are optional. For instance, a function that creates a new window in a GUI library may have dozens of arguments, most of them optional, which are best specified by names:
    w = Window{ x=0, y=0, width=300, height=200,
                title = "Lua", background="blue",
                border = true
              }
The Window function then has the freedom to check for mandatory arguments, add default values, and the like. Assuming a primitive _Window function that actually creates the new window (and that needs all arguments), we could define Window as follows:



    function Window (options)
      -- check mandatory options
      if type(options.title) ~= "string" then
        error("no title")
      elseif type(options.width) ~= "number" then
        error("no width")
      elseif type(options.height) ~= "number" then
        error("no height")
      end
    
      -- everything else is optional
      _Window(options.title,
              options.x or 0,    -- default value
              options.y or 0,    -- default value
              options.width, options.height,
              options.background or "white",   -- default
              options.border      -- default is false (nil)
             )
    end