Home Accessibility Courses Twitter The Mouth Facebook Resources Site Map About Us Contact
Our telephone lines have been repaired - sorry if you couldn't get through
+44 (0) 1225 708225 / 01225 708225
Formally open 9 a.m. to 5 p.m. (but usually around much longer

Python, Lua, Tcl, C and C++ training - public course schedule [here]
Private courses on your site - see [here]
Please ask about maintenance training for Perl, PHP, Java, Ruby, MySQL and Linux / Tomcat systems
Programming Standards in Lua

I like my freedom to do as I please. But my freedom, thoughtlessly used, can make a lot of work for others, and indeed can restrict their freedom. We need some groundrules - in a programming sense, some coding standards

Why have standards?

1. So your colleagues can follow your code
2. So that you can follow your own code later
3. So that your code is robust
4. So that your code is easy to debug and maintain
5. So that your code is easy to test
6. So that your code is reusable where possible, and written to encourage its reuse
7. So that it's a pleasure to work with your code

By writing code which is logically structured, easy to follow, and contains all the extra information that future people who need access to the code might require, you'll be doing both them a big favour. And you'll be doing yourself a big favour too, as you'll be applying guidelines early on and thinking through controlled and reusable code right from the beginning.


Naming Standards

Consider the following variable names

They could all be used to contain the number of delegates in a class, and the code will function identically - but the earlier names suggested here are confusing, and the name "numberInClass" is very much the best. It's more typing than "nic" or "j"; conventional wisdom is that a short or very short name is accepatble and even encouraged for variables with limited or very limited scope. You'll see that with the common use of "k" and "v" from pairs and ipairs.

A consistency within names is also encouraged:
  noinclass -- abbreviated keywords
  numberInClass -- Camel Case
  i_numberInClass -- Hungarian Notation / tells data type

Look at your existing code and if there's already a standard, stick with it. Otherwise choose one. Consider also:
  tokenColour -- UK English
  tokencolor -- US English

And think how long you could spend looking for errors in programs that have mixed up the two. Don't care which you use - just choose one!

Some specifics from http://lua-users.org/wiki/LuaStyleGuide

1. Booleans - It can be helpful to prefix Boolean values or functions used as predicates with is, such as is_directory rather than directory (which might store a directory object itself).

2. Lua internal variable naming - The [Lua 5.1 Reference Manual - Lexical Conventions] says, "As a convention, names starting with an underscore followed by uppercase letters (such as _VERSION) are reserved for internal global variables used by Lua." These are often constants but not necessarily, e.g. _G.

3. Constants naming - Constants, particularly ones that are simple values, are often given in ALL_CAPS, with words optionally separated by underscores (e.g. MAXLINES in PiL2, 4.3 and also the Markov example in PiL2, Listing 10.6).

4. Module/package naming - Module names are often nouns with names that are short and lowercase, with nothing between words. At least, that's the general pattern noticed in Kepler: luasql.postgres (not Lua-SQL.Postgres). Examples: "lxp", "luasql", "luasql.postgres", "luasql.mysql", "luasql.oci8", "luasql.sqlite", "luasql.odbc", "socket", "xmlrpc", "xmlrpc.http", "soap", "lualdap", "logging", "md5", "zip", "stable", "copas", "lxp", "lxp.lom", "stable", "lfs", "htk".

5. The variable consisting of only an underscore "_" is commonly used as a placeholder when you want to ignore the variable

* Module names are MOST important as they will have the widest scope
* Global and function name are next most important
* Variable names are important too

Code Structure

Each function should perform what's described as a single logical operation. If you write a function that formats a string AND outputs the result, sooner or later you'll need to format the string and then add it on to the end of another string and your original function won't do the job for you.

Reduce scope. Use locals rather than globals whenever possible. Globals have larger scopes and lifetimes and therefore increase [coupling] and complexity. [1] Don't pollute the environment. In Lua, access to locals is also faster than globals [PIL 4.2] since globals require a table lookup at run-time, while locals exist as registers. In Lua, globals are sometimes the result of mispellings and other lurking errors in your code.

To test whether a variable is not nil in a conditional, it is terser to just write the variable name rather than explicitly compare against nil. Lua treats nil and false as false (and all other values as true) in a conditional

The goto was introduced in Lua 5.2. Use the tail call (http://www.lua.org/pil/6.3.html) which will jump you from one function into the next by all means, but be careful with the goto. It does provide you with a way out of nested loops, but it can also lead to spaghetti code.

Code Layout

It's convention in Lua to use three spaces to inset blocks, and never to use tabs. Code insetting makes huge sense as it helps the reader see, very quickly, what goes with what. Too few spaces (e.g. one), and you'll still have problems looking up and down the screen and working out what goes with what. Too many spaces (8 or a tab, for example) and by the time you get a few nested blocks you'll have lost half of you window to empty space when you edit the file. In Python we recommend 4 spaces; three's the convention in Lua, through why that is is now lost in the history of time. It's a good standard anyway.

Design Patterns

A design pattern is the implementation of an algorithm in a standard way. By using tried, tested (and repeated) arrangements of code, you learn from the experience of others who have set up and established those design patterns. With Lua beinga small language, it's left to the programmer to write a block of code to do what would be a oneline function call in other languages, and so the design patterns for those blocks become very important. You'll see examples of design patterns in use throughout the notes and in the extra examples on our web site, and during the course I will have used the term "pattern" when I have introduced them.

Additional Information (code metadata)

If you're reading this as part of a course, you'll already have heard me hammering on from the beginning about the need to comment your code. That's so that you can work out yourself what it does when you come back to it, as well as letting others work out what it does. But is is NOT a case of "the more comments the better" ... if you find yourself commenting every line of a program for your colleagues then
  a) You should send your colleagues on a course to learn Lua itself
  b) You should consider how readable you have made your code through the rest of the standards.
So what would I recommend?

a) A header block

Each file to have author, date, version, note of product(s) it's used in or purpose, Copyright / license, known issue list

b) Each named block of code

Description of what it does, note of input and output parameters, and any globals that are required / used.

c) Within the named blocks of code

i) A description of every group of lines. I'm intentionally being woolly with that wording - I would expect a group to have a typical length of perhaps 5 to 20 lines, but single lines could be a "group" on occasions - and you could even have an empty group noting something like "This is where you can add in code later". On occasions, groups may be longer but that suggests there would be repetition in the code, and potential for loops or named blocks to shorten the group.

ii) Individual line comments. Where something obscure / clever is being done, add a comment to inform the reader. If this starts happening frequently, consider refactoring the code to make it more readable.

iii) Variable description. Especially with global variables, you may wish to include a desctiption of what they contain, how wide they are scoped, and what units are used for values held in them.

d) Blank lines and separators

A comment line comprised completely of "-" signs between each lua function definition.

Blank lines to split groups further into subgroups

Blank lines to emphasise the group descriptions

e) Sample outputs and data

It is very VERY valuable if you're writing Lua code that extracts information from files / strings to include, within a comment, some sample data, and if that data's written to a particular standard include a reference to that standard.

It's also useful to include sample runs of your program showing what it should look like (complete program) or how the code should be called (file of functions).

f) end of what?

Lua uses "end" to terminate blocks. Should you add a comment to say what you're ending?

There's an example of comment code standards at http://sputnik.freewisdom.org/en/Coding_Standard which shows examples of header blocks, etc

Testing, revision Control Systems and release control.

If you've even spent time debugging a program / sorting out an issue based on a customer report, only to find that the problem had been fixed anyway in the most recent release, then you'll know the importance of having some sort of versioning system. This doesn't just apply to Lua! We know it's very irritating as a user to be asked to upgrade to the latest version before a support team will look at an issue, but countless hours have been lost over the years fixing code and searching out problems that someone else has already searched out and fixed.

On larger projects, where multiple software engineers may be working on the same code, you need to consider how you'll intereact if two people need to edit the same code at the same time. You shouldn't just leave it to chance. Here's a scenario where things could go wrong: "A" reads a file from the central repository and works on it. "B" reads the same file, makes a small change to fix a bug and saves it away. "A" then saves his changes, overwriting the bug fix done by "B" ...

The solution is to use a version / revision control system, where files are checked out of and back into the central repository, ensuring that conflicting operations don't happen. Such systems can also record changes version by version, so should the need arise you can look back through the history of the code, rebuild old versions, etc. Some of the names you may come across are SCCS, RCS, CVS, Subversion, ClearCase and Git. Some of these are local only, some are client / server, some are distributed. And some are Open Source, others proprietory.

On a larger project, a more formal issue reporting / known bug status system should also be considered.

A test harness is a program which itself runs your code or parts of it with specific inputs / in a predefined way, asserts what the results should be, and checks that these assertions work. Rather than write your own test harness from scratch, a number are available which will allow you to write shorter test pieces of code, and have standard code within the harness manage the checking of the assertions, and monitoring the number of successes, failures, etc to provide you with a complete test system. But Lua's a small language - and these test harnesses don't ship with the download. You can find a whole lot listed at http://lua-users.org/wiki/UnitTesting. Worth a look:
Lunit - http://www.nessie.de/mroth/lunit/
LuaUnit - http://phil.freehackers.org/programs/luaunit/

Software Licensing

The choice of software license for your Lua code depends on your goals and what type of code it is (e.g. module or application). Licensing choice is particularly significant for modules, which are often distributed with other modules and applications.

There are advantages to licensing Lua modules, or at least those intended for the general Lua community, under the same terms as Lua itself, which as of version 5.0 is the MIT license. Not only is the MIT license a very simple to understand and unrestrictive license (in fact, no more restrictive than Lua itself), but consistency in licensing between modules and with Lua allows simplified distribution of bundles of modules and Lua together, such as for distributions and embedded versions of Lua. (This basic approach has worked very well in the past for the Perl language, which has thousands of modules most entirely under an MIT-like license called the Artistic License, under which Perl is also distributed. Perl modules often indicate their licensing simply with the statement "Licensed under the same terms as Perl itself.") Those advantages of using an MIT license are reduced, though not eliminated, if your Lua module acts as a binding to some C library released under some very different license such (L)GPL or a closed source one since the latter code impose stronger restrictions on distribution anyway. Avoid, whenever possible, writing your own license or adding additional clauses but rather consider strongly the words of warning about consistency at the top of this document since inconsistency is a detriment to reusability, and reusability is a main advantage of module.

We are trainers not legal experts. If in doubt, please seek advise.


There's a set of uncommented / untested functions ("shows you how") coding [here]. The functions, better documented internally, nicely set out, and with a built in test harness are [here].
(written 2012-04-06, updated 2012-04-07)

Associated topics are indexed as below, or enter http://melksh.am/nnnn for individual articles
G906 - Well House Consultants - Programming Standards
  [2364] Getting it right from the start - new programmers - (2009-08-17)
  [2363] Alpaca Case or Camel Case - (2009-08-16)
  [2322] Looking for a practical standards course - (2009-08-05)
  [1852] Perl and Blackberries - (2008-10-23)
  [1679] PHP - Sanitised application principles for security and useability - (2008-06-16)
  [1596] Selling curry to the chinese takeaway - (2008-03-31)
  [945] Code quality counts - (2006-11-26)
  [356] Sudoku helper or sudoku cheat - (2005-06-23)
  [343] Should I use structured or object oriented? - (2005-06-10)
  [272] More to programming than just programming - (2005-04-08)
  [148] Programming in isolation - (2004-12-11)

U199 - Programming Standards in Lua

Back to
Once upon a Maundy Thursday
Previous and next
Horse's mouth home
Forward to
The goto statement in Lua
Some other Articles
Can I cycle or ride my mobility scooter on the pavement?
Shopkeepers take an Easter break too
Binary / bitwise operations in Lua with the standard bit32 library
The goto statement in Lua
Programming Standards in Lua
Once upon a Maundy Thursday
Weak references in Lua - what are they, and why use them?
Melksham Business Newsreel
Kicking up a stink, the Victorian way?
How can I run multiple web servers behind a single IP address?
4750 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95 at 50 posts per page

This is a page archived from The Horse's Mouth at http://www.wellho.net/horse/ - the diary and writings of Graham Ellis. Every attempt was made to provide current information at the time the page was written, but things do move forward in our business - new software releases, price changes, new techniques. Please check back via our main site for current courses, prices, versions, etc - any mention of a price in "The Horse's Mouth" cannot be taken as an offer to supply at that price.

Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2017: 404 The Spa • Melksham, Wiltshire • United Kingdom • SN12 6QL
PH: 01144 1225 708225 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/mouth/3685_Pro ... n-Lua.html • PAGE BUILT: Sat May 27 16:49:10 2017 • BUILD SYSTEM: WomanWithCat