Page 1 of 1

General Code Formatting?

Posted: Fri Jul 08, 2016 12:39 am
by HydratedToast
I think I format my code well, however I may be missing something. What are the general rules for formatting your code?

Re: General Code Formatting?

Posted: Fri Jul 08, 2016 5:15 am
by ivan
Whatever works for you, really. 99% of the time you'll be the only person going back and reading your own code.
If you make public modules and libs, then here are some tips:
https://luapower.com/coding-style

Re: General Code Formatting?

Posted: Fri Jul 08, 2016 6:00 am
by Inny
Kikito has a short, but good write up on how to write modules: http://kiki.to/blog/2014/03/30/a-guide- ... a-modules/

I think the thing that works best is more knowing the principles, idioms, customs, social mores, etc. rather that how it should look. For instance, a Module contains functions, where as an Object contains methods. The difference is the dot versus the colon operators when defining a function (this is in part one of kikito's guide). The expectation there is what's key. You expect a module to give you back a bunch functions, not that it would be an object.

Another idea is that if you are making an object, that the function which creates the object is called "new" and lives inside a module. In javascript you would see the function named "create" for building an object. If I want access to the "Class" that an object belongs to, I'll typically find it with getmetatable. I should be able to tell that two objects are of the same class by comparing their metatables (although I shouldn't be doing that kind of object inspection).

Basically, things are written to meet with expectations. While ivan is right that you're most likely going to be the only person reading your own code, you will come to hate yourself for writing sloppy code when you return to code you haven't read in months and can't understand it.

Re: General Code Formatting?

Posted: Fri Jul 08, 2016 10:56 am
by zorg
As for stylistic and not semantic formatting, difference between capitalization and word-separation of variable names, for example;

lowercase, UPPERCASE, CamelCase, pascalCase, under_scored... among more "unorthodox" types.
Indentation by spaces or tabs, also the difference between line-starting indentation and alignment.
(Example: I use 4-space wide tabs for indentation, but i align most assignment lines with spaces so the '=' symbols are neatly under one another)
Whether you put spaces or not between symbols like /-*+=()[]{}, etc...
Whether you place the first line in an array on the line with the opening { bracket, or below it.

Small things like these might make code look more readable, but it is, of course, wholly subjective.