• Programming Styles
    96 replies, posted
As everybody who programs knows, there is a rainbow array of different programming styles. Some are for minimalists, and others are for 'readability'; or to be almost like reading a book. Although, some are very under developed and lack consistency. Which is why I'm making this thread. Tell us about your style, why you do it, or the benefits of using it. I'll share my opinion on semicolons first. Semicolons I usually program with Java, so I'm used to using semicolons. I'll use semicolons in Lua because I'm just so used to it that it happens without me thinking about it. Although semicolons aren't required in any way when using Lua, I prefer them because they give me a sense of completion in the line. I feel like snippets such as [lua]local var = 0[/lua] don't quite end at zero, but continue on to the wrest of the lines. I know in my head they don't, but I interpret it as I would other languages I'm more familiar with. (C/C++/Java) [lua]local var = 0;[/lua] Ah now it feels complete. You can all complain about how it's dumb and adds extra bytes to the file size now.
File size in text files (lua) doesn't really matter unless you got 200,000 lines of code or more. I've seen plenty of styles, one of the styles that I like looking at but not using is putting the first digit of variables value type at the beginning of it's name, ergo: [code]local bVar = false local sVar = "yep" local iVar = 300 local fVar = 0.03 local tVar = {}[/code] But anyways, I've tried 3 styles: Names, including spaces [code]local var_name_here = 0[/code] CamelCaps [code]local VarNameHere = 0[/code] But so far, my favourite is camelBack, because it looks very tidy, can be easily readable and is commonly used in C# programming. [code]local varNameHere = 0[/code]
I use semicolons when onelining several methods at once I use underscores on functions that I save as "backups" because I'm detouring them I tab like a fucking bitch. Every new for, if, inline function, or method called with a long line of arguments is given its own tab. [editline]20th May 2014[/editline] And I use UpperCamelCase
localvar CONST_VAR functionName {table, entries} and (function, arguments) no semicolons
lowerCamelCase for variables and function names alike, UPPER_WITH_UNDERSCORES for constants, semicolons everywhere.
I am a practitioner of inverted mongoose. [code]if not self.Panels.Menu then local p = vgui.Create( "DFrame" ) p:SetTitle( "RPG Setup" ) p:SetDraggable( true ) p:ShowCloseButton( true ) p:SetDeleteOnClose( false ) p:SetSize( ScrW( ) / 2, ScrH( ) / 2 ) p:Center( ) local sheet = vgui.Create( "DPropertySheet", p ) sheet:Dock( FILL )[/code] Rules: No semicolons Don't talk about semicolons Spaces after every delimiter like ( { , No non-essential parenthesis Avoid lambdas - declaring a function is generally better unless you need to encapsulate No c operators ( ! // /* */ ) Variable names are all lower case, properties and functions are all in proper case. I'm also the kind of guy who, when you have a bunch of declarations in a row, tabs them all out so that the = and the value line up
Embrace the ~= operator. Burn the != operator.
I know exactly what you mean. Look at my code on this post here: [url]http://facepunch.com/showthread.php?t=1394975[/url]. I have so many unnecessary lines and organization tactics, but I actually have OCD, and that keeps my code tight.
[QUOTE=Willox;44862536]Embrace the ~= operator. Burn the != operator.[/QUOTE] Isn't != garrycode while ~= standard lua?
Some snippets that should speak for themselves: [CODE] if (someCondition () and thisIsABoolean) -- parentheses here for readability or (someOtherConditionsOrSomething ()) -- align the conditions or (more and (evenMore () or not lessThanBefore ())) -- condition description as comments, if necessary or (more and (evenMore32 () or not lessThanBefore2 ())) then -- gets it's own line if it improves readability finallyWeCameToAnEnd () end [/CODE] [CODE]local data = { something = "here and there", ["something else"] = "value" -- bad, mixing styles }[/CODE] [CODE]cube:SetPos (pos + Vector ( m_sin (m_cos (ct) * 4 + ct * 2.2 + i + 90) * 37, m_cos (m_sin (ct) * 4.5 + ct * 2.3 + i + 90) * 37, m_sin (m_cos (ct) * 5 + ct + i) * 37 -- it's all about the alignment ))[/CODE] No semicolons. Spaces before/after parenthese pairs, after commas, before/after operators. No non-essential parenthesis, except for cases where it looks confusing without them. Lambdas: yes, but if it's more than a few lines I will probably make it a local function instead and put it right above it. No C syntax, I want to use 100 % lua without GMod-modified bleh. Variable names are all lower case (with_underscores_as_spaces), function names are camelCase. Empty lines: where they make sense and improve readability. Common variable names: i(, j) = indices/counters, k = key, v = value ply = player, ret = return value (in cases I don't return immediately), typ = type (i.e. string that type() returns) for k, v in [B]next, TABLENAME[/B] do end instead of for k, v in [B]pairs(TABLENAME)[/B] do end
[QUOTE=MattJeanes;44862726]Isn't != garrycode while ~= standard lua?[/QUOTE] The following were added by Garry: [code] /* ... */ // ... != ! && || continue [/code] Semicolons are valid with stock Lua.
I thought continue was Lua 5.2?
[QUOTE=MattJeanes;44862949]I thought continue was Lua 5.2?[/QUOTE] Garry's Mod hasn't got Lua 5.2 nor does LuaJIT (at least the version Garry's Mod is using) implement continue.
Don't use GLua syntax unless you want to limit the tooling that you can work with in your project. As an example, I use the SublimeLinter plugin to let me know when I made a syntax error while writing code. I would have to recompile lauc.exe if I wanted to be able to use GLua syntax, which isn't worth it and doesn't provide enough benefits.
Here's an example of two functions in my admin mod. [t]http://ss.infd.us/linux/2014-05-20@23-45-49.png[/t] - No semicolons. [highlight]Ever.[/highlight] - No parenthesis around if statements: rather than [I]if (a == b) then[/I], I use [I]if a == b then[/I] - No "airy" parenthesis - All lua operators, no C. - Comments on the same line as code, it helps to clarify what the comment is describing. If it's summarising a function, neatly before the function, or "section" of code. - Lowercase variable names. - Empty lines between functions. - One "tab" per function block, not two. - One space after commas, one space before and after operators. - No lambdas unless absolutely necessary. - Function names CamelCase.if (a == b) then
I like some of your styles. I think I'm going to adopt some of the more strict Lua styles, which is to have no semicolons, and only use vanilla Lua operators.
I do like the /* */ comments though, looks better imo and easier to write. Also what are replacements for !/&&/||?
[QUOTE=MattJeanes;44863255]I do like the /* */ comments though, looks better imo and easier to write. Also what are replacements for &&/||?[/QUOTE] && = and || = or [code] if x and y then ... if x or y then ... [/code]
Of course, but there's no symbols or anything? I prefer and/or even so - just wondering
[QUOTE=MattJeanes;44863354]Of course, but there's no symbols or anything? I prefer and/or even so - just wondering[/QUOTE] Nope
[lua] _____________________variable = 0;;;;; // Sets _____________________variable to be equal to 0 -- Johnny Guitar local function _____HolyShit(__dicks, dick);; // Create a new function that accepts a local variable __dicks and a global variable dick -- Johnny Guitar end;;; [/lua]
[img]http://i.imgur.com/rETb4Y4.png[/img]
[lua] local function CreateSomeInfo( pl ) pl.PlayerInfo = pl.PlayerInfo or {} pl.PlayerInfo[ "somekey" ] = true -- Comments are indented if pl.PlayerInfo[ "somekey" ] then pl:ChatPrint( "You have the key!" ) end pl:NetworkInfo() --[[while true do print("test") end]] end [/lua] Also I never use ~=, only !=
Word of warning: Never ever use /* */ This is handled by Garry's preprocessor and beaks line numbering. Try running this in a file: [code] /* a a a */ error"hi" [/code]
[QUOTE=Python1320;44866845]Word of warning: Never ever use /* */ This is handled by Garry's preprocessor and beaks line numbering. Try running this in a file: [code] /* a a a */ error"hi" [/code][/QUOTE] Oh god, debugging DarkRP jobs.lua and shipments.lua is such fun with the comments on top of the file :v: All these kids coming to Facepunch: "I don't see the error on line ...!".
Overall is: [code] [type][get/set][CamelCase(Function/Method)Name] [type][CamelCase(Variable/Class/Struct)Name] //LUA local tTableOfContents = { sTitleName = "It", sAuthorName = "Stephen King", iPagesCount = 500 }; if(isSomething(oThing) and (true == bVar)) then --Got this Doing alot of C++ xD oEnt:SetPos(); -- For Gmod realted methods end // C, C++, AnsiC typedef class Vector { private: double X; // .... and so on public: class Vec& getNormalized(); class Vec& Normalize(); double getAbs(); friend Vector operator+(Vector, Vector); } cVec; // Pro*C EXEC SQL SELECT //some stuff here INTO :sTableName FROM TableName WHERE Condition; [/code]
[QUOTE=Python1320;44866845]Word of warning: Never ever use /* */ This is handled by Garry's preprocessor and beaks line numbering. Try running this in a file: [code] /* a a a */ error"hi" [/code][/QUOTE] I hate my life.
1) Lower camelCase for locals/parameters 2) Upper CamelCase for everything else 3) No semicolons 4) Always use verbose operators, e.g: [I]not[/I], [I]and[/I], [I]or[/I] 5) Spaces after commas and delimiters [I]unless[/I] no arguments/key-values are passed, e.g: [lua] func1( a, b, c ) func2() local tbl1 = { a, b, c } local tbl2 = {} [/lua] 6) Document [I][B][U]everything[/U][/B][/I] Example: [lua] --- All functions are available also as methods of the complex number class. -- Operators work with both numbers and complex numbers. -- @author Pac -- @classmod complex local complex = {} complex.__index = complex complex.__newindex = function() error( "attempt to index complex value" ) end --- Constructors -- @section Constructors --- Creates a new complex number -- @tparam[opt=0] number real -- @tparam[opt=0] number imag -- @treturn complex -- @usage local c = complex.New( 1, 1 ) function complex.New( real, imag ) local obj = {} obj.Real = real or 0 obj.Imag = imag or 0 setmetatable( obj, complex ) return obj end --- Fields -- @section Fields --- Real part complex.Real = 0 --- Imaginary part complex.Imag = 0 --- Functions -- @section Functions --- Returns whether the given complex numbers are equal -- @tparam complex c1 -- @tparam complex c2 -- @treturn bool function complex.Equal( c1, c2 ) return c1.Real == c2.Real and c1.Imag == c2.Imag end --- Returns the sum of the given complex numbers -- @tparam complex c1 -- @tparam complex c2 -- @treturn complex function complex.Add( c1, c2 ) local real = c1.Real + c2.Real local imag = c1.Imag + c2.Imag return complex.New( real, imag ) end --- Returns the difference of the given complex numbers -- @tparam complex c1 -- @tparam complex c2 -- @treturn complex function complex.Sub( c1, c2 ) local real = c1.Real - c2.Real local imag = c1.Imag - c2.Imag return complex.New( real, imag ) end [/lua]
Dude you got more comments than code there
[QUOTE=MattJeanes;44868077]Dude you got more comments than code there[/QUOTE] But it's [url=http://gearsgaming.net/documentation/misc/doc/index.html]so pretty :suicide:[/url] [editline]21st May 2014[/editline] I only really use LDoc commenting in modules like this that I use tons of places and even share with select people. It doesn't take long either, it's primarily a copy-paste job.
Sorry, you need to Log In to post a reply to this thread.