• Your Idea of 'Pretty' Code?
    101 replies, posted
An example of beautiful code in my opinion: [code] hook.Add("Init", "PrintIdiot", function() local idiot = LocalPlayer() if idiot:Name() == "Wavie" then print(idiot:Name() .. " is an idiot.") else print(idiot:Name() .. " is cool.") end end) [/code] What's your idea of "pretty" code? Also, are you an OCD coder? I know I am. I literally make sure that empty lines don't have spaces/indents within them. PS - Why did FPtje make DarkRP's code consist of spaces instead of tabs? It [u]seriously[/u] irritates me.
[B]My[/B] guidelines: - [I][B][U]INDENT ONLY WITH TABS[/U][/B][/I] - If you have more than 1 argument inside parenthesis, space everything. - Never space brackets - Never space mathematical expressions [I]unless[/I] it's long stuff and you need spacing to make sure you're not making mistakes - Space after commas - Break conditions should be written in 1 line ( if condition then return end ) - Only use parenthesis if you have to ( [B]if true then[/B], rather than [B]if ( true ) then[/B] ) - Have an empty line between different functions - Have an empty line between different parts of the code, if there's not relation between them
[QUOTE=JasonMan34;52097893][B]My[/B] guidelines: - [I][B][U]INDENT ONLY WITH TABS[/U][/B][/I] - If you have more than 1 argument inside parenthesis, space everything. - Never space brackets - Never space mathematical expressions [I]unless[/I] it's long stuff and you need spacing to make sure you're not making mistakes - Break conditions should be written in 1 line ( if condition then return end ) - Only use parenthesis if you have to ( [B]if true then[/B], rather than [B]if ( true ) then[/B] - Have an empty line between different functions - Have an empty line between different parts of the code, if there's not relation between them[/QUOTE] I agree 100%, except for the mathematical expressions. I always space arithmetical expressions and commas. However, I never space brackets/parenthesis. I hate that shit. It looks ugly as hell.
[CODE] -- prefer vanilla lua syntax if SERVER then -- no parentheses util.AddNetworkString( "addonname_net_description" ) -- network strings always get added first resource.AddFile( "models/ice/bd_chance_lg.mdl" ) -- then resource library calls end -- localizing libraries versus single functions local string = string local rand = math.random -- tables local tbl = { ["stringkeys"] = "like this", [23490235] = "basically all keys like this", -- unless it's a metamethod... __index = function( t, k ) return 0xAA289 end, -- comma after the last key every time } -- comments detailing what functions do go one line above, but everything inside and in between is double-spaced unless it's something like two calls to the same function two separate times local myfunction = function( a, b, c ) -- spaces for padding inside parentheses and between args -- i would NOT write this as local function myfunction( a, b, c ) if not c then return a end return a < b and c or a -- i like my faux ternaries end print( myfunction( 4, 1, 7 ) ) for k,_ in next, tbl, nil do -- next, tbl(, nil) instead of pairs( tbl ) because i like the way it looks, not because it's microscopically quicker - also, no space between k,_ -- could write for k in, but I tend to keep the dummy _ there anyway print( tbl[k] ) -- no spaces for padding square brackets print( "tbl[" .. k .. "] == " .. tbl[k] ) -- always double-quote strings and space between concatenated values end hook.Add( "InitPostEntity", "addonname_hook_InitPostEntity", function() -- i tend to choose hierarchy over useful description with hook names - sue me if ( not tbl[54321] ) and ( os.time() > 45 ) then -- parenthese master somefunction{ ... } -- no parentheses for calls with a single table constructor argument, but will use parentheses if it's just a single string end end ) print( #( tbl ) ) -- wrap counted array in parentheses print( 5 * 8 - 2 ) -- space math local ply_meta = FindMetaTable( "Player" ) -- metatables suffixed with _meta -- obtains the size of the player's buttocks function ply_meta:GetCheekSize() return self.cheek1 + self.cheek2 end -- sets the size of the player's buttocks function ply_meta:SetCheekSize( x ) local mat = hardwarestore.buy( "Paint Thinner" ) local theneedle = needle( mat, x ) self:Inject( theneedle ) end -- ????????? local i = util.Stack() i:Top() i:Push( "shit" ) i:Pop() [/CODE]
[QUOTE=IceGT_;52097953]-snip-[/QUOTE] It's definitely different than my taste. However, I can appreciate the level of organization that you put into your code.
[lua] hook.Add("Init", "PrintIdiot", function() local name = LocalPlayer():Name() print(name == "Wavie" and name.." is an idiot" or name.." is not cool") end) [/lua]
befunge
[QUOTE=Coffeee;52098068][lua] hook.Add("Init", "PrintIdiot", function() local name = LocalPlayer():Name() print(name == "Wavie" and name.." is an idiot" or name.." is not cool") end) [/lua][/QUOTE] Don't really think short circuit coding is appealing, honestly.
[code] -- ## ----------------------------------- Actors2 ---------------------------------- ## -- -- RemoveEmptyKey() -- Perform a loop through the string keys in the ActorsTable and searchs -- for the one that matches the NULL entity and remove it. -- ## ------------------------------------------------------------------------------ ## -- function TOOL:RemoveEmptyKey( ply ) for k, v in SortedPairs ( table.GetKeys( ActorsTable[ply:SteamID()] ) ) do if tostring( v ) == "NextBot [NULL]" then ActorsTable[ply:SteamID()][v] = nil end end end [/code] One liners, anyone? :v:
Install glualint and use the pretty print feature. That's my style :v:
Depends on my mood and the time of day. I switch between camel case and underscores on a daily basis and still somehow have the gall to complain about garry's naming conventions. [QUOTE=FPtje;52098461]Install glualint and use the pretty print feature. That's my style :v:[/QUOTE] I really need to give this a shot.
First requirement of pretty code, don't write it in Lua.
Space after every comma, no spaces after or before parenthesis ( why tf do people do that it just looks weird to me ). I had to do a lot of python for awhile, and that language uses spaces instead of tabs so I have my text editors set to indent using spaces instead of actual tabs and it doesn't bother me.
Functions should be no longer than 3 lines, 5 if they absolutely must be. All names should be descriptive enough to substitute for commenting and the code should read like well-written prose Bonus points for naming the madman teaching this
[QUOTE=H4ngman;52098607]Functions should be no longer than 3 lines, 5 if they absolutely must be. [/QUOTE] That's a little OCD is it not? I just put everything one line and hope it works :hammered:
[QUOTE=Wavie;52097872]An example of beautiful code in my opinion: [code] hook.Add("Init", "PrintIdiot", function() local idiot = LocalPlayer() if idiot:Name() == "Wavie" then print(idiot:Name() .. " is an idiot.") else print(idiot:Name() .. " is cool.") end end) [/code] What's your idea of "pretty" code? Also, are you an OCD coder? I know I am. I literally make sure that empty lines don't have spaces/indents within them. PS - Why did FPtje make DarkRP's code consist of spaces instead of tabs? It [u]seriously[/u] irritates me.[/QUOTE] "my code is the prettiest"
[QUOTE=Leystryku;52099324]"my code is the prettiest"[/QUOTE] In my opinion my code is the prettiest :v:
howcome your avatar is the lua icon ?
[code] --[[ Brief description of the responsibility of a file FunctionAddedToGlobalNamespace1(arg1 :: type, arg2 :: type, arg3 :: type) :: return Brief description of what the function does FunctionAddedToGlobalNamepace2(index :: number) :: number : : ]] --All includes must go at the top of a file include("foo.lua") include("bar.lua") --Any clarifying comment needed when I inevitable need to change this function function FunctionAddedToGlobalNamespace1(arg1,arg2,arg3) local a,b,c = 1,{},"Hello, world!" --Keep multiple declarations below 5 per line, do not multiple declare when initializing a table with more than 1 value local d = 4 --You can align with spaces the first time you write something, but not after it has been committed with git (it clutters up the git log) print(arg1,a,arg2,b,arg3,c) end function FunctionAddedToGlobalNamespace2(n) --If there's a especially complicated bit of code, comment before and leave a blank line after local function f(a,b,n) return n == 0 and b or f(b,a + b,n - 1) end return f(0,1,n) end [/code] Also, GLuaLint is fantastic.
Lisp is a beautiful language [code](defparameter *wizard-nodes* '((living-room (you are in the living-room. a wizard is snoring loudly on the couch.)) (garden (you are in a beautiful garden. there is a well in front of you.)) (attic (you are in the attic. there is a giant welding torch in the corner.)))) (defparameter *wizard-edges* '((living-room (garden west door) (attic upstairs ladder)) (garden (living-room east door)) (attic (living-room downstairs ladder)))) (defun dot-name (exp) (substitute-if #\_ (complement #'alphanumericp) (prin1-to-string exp))) (defparameter *max-label-length* 30) (defun dot-label (exp) (if exp (let ((s (write-to-string exp :pretty nil))) (if (> (length s) *max-label-length*) (concatenate 'string (subseq s 0 (- *max-label-length* 3)) "...") s)) "")) (defun nodes->dot (nodes) (mapc (lambda (node) (fresh-line) (princ (dot-name (car node))) (princ "[label=\"") (princ (dot-label node)) (princ "\"];")) nodes)) (defun edges->dot (edges) (mapc (lambda (node) (mapc (lambda (edge) (fresh-line) (princ (dot-name (car node))) (princ "->") (princ (dot-name (car edge))) (princ "[label=\"") (princ (dot-label (cdr edge))) (princ "\"];")) (cdr node))) edges)) (defun graph->dot (nodes edges) (princ "digraph{") (nodes->dot nodes) (edges->dot edges) (princ "}")) (defun uedges->dot (edges) (maplist (lambda (lst) (mapc (lambda (edge) (unless (assoc (car edge) (cdr lst)) (fresh-line) (princ (dot-name (caar lst))) (princ "--") (princ (dot-name (car edge))) (princ "[label=\"") (princ (dot-label (cdr edge))) (princ "\"];"))) (cdar lst))) edges)) (defun ugraph->dot (nodes edges) (princ "graph{") (nodes->dot nodes) (uedges->dot edges) (princ "}")) (defun dot->png (fname thunk) (with-open-file (*standard-output* (concatenate 'string fname ".dot") :direction :output :if-exists :supersede) (funcall thunk)) (ext:shell (concatenate 'string "dot -Tpng -O " fname ".dot"))) (defun dgraph->png (fname nodes edges) (dot->png fname (lambda () (dgraph->dot nodes edges)))) (defun ugraph->png (fname nodes edges) (dot->png fname (lambda () (ugraph->dot nodes edges)))) ;(defun run () ; (ugraph->png "wizard" *nodes* *edges*))[/code]
[QUOTE=Wavie;52097872]An example of beautiful code in my opinion: [code] hook.Add("Init", "PrintIdiot", function() local idiot = LocalPlayer() if idiot:Name() == "Wavie" then print(idiot:Name() .. " is an idiot.") else print(idiot:Name() .. " is cool.") end end) [/code] What's your idea of "pretty" code?[/QUOTE] [code] hook.Add("Init", "PrintIdiot", function() local name = LocalPlayer():Name() local consensus = name == "Wavie" and "an idiot" or "cool" print(("%s is %s."):format(name, consensus)) end) [/code] [editline]13th April 2017[/editline] [QUOTE=code_gs;52099871]Lisp is a beautiful language [/QUOTE] For a better comparison, could you translate the code in the OP to lisp and show us that?
[QUOTE=IceGT_;52097953][CODE] -- prefer vanilla lua syntax if SERVER then -- no parentheses util.AddNetworkString( "addonname_net_description" ) -- network strings always get added first resource.AddFile( "models/ice/bd_chance_lg.mdl" ) -- then resource library calls end -- localizing libraries versus single functions local string = string local rand = math.random -- tables local tbl = { ["stringkeys"] = "like this", [23490235] = "basically all keys like this", -- unless it's a metamethod... __index = function( t, k ) return 0xAA289 end, -- comma after the last key every time } -- comments detailing what functions do go one line above, but everything inside and in between is double-spaced unless it's something like two calls to the same function two separate times local myfunction = function( a, b, c ) -- spaces for padding inside parentheses and between args -- i would NOT write this as local function myfunction( a, b, c ) if not c then return a end return a < b and c or a -- i like my faux ternaries end print( myfunction( 4, 1, 7 ) ) for k,_ in next, tbl, nil do -- next, tbl(, nil) instead of pairs( tbl ) because i like the way it looks, not because it's microscopically quicker - also, no space between k,_ -- could write for k in, but I tend to keep the dummy _ there anyway print( tbl[k] ) -- no spaces for padding square brackets print( "tbl[" .. k .. "] == " .. tbl[k] ) -- always double-quote strings and space between concatenated values end hook.Add( "InitPostEntity", "addonname_hook_InitPostEntity", function() -- i tend to choose hierarchy over useful description with hook names - sue me if ( not tbl[54321] ) and ( os.time() > 45 ) then -- parenthese master somefunction{ ... } -- no parentheses for calls with a single table constructor argument, but will use parentheses if it's just a single string end end ) print( #( tbl ) ) -- wrap counted array in parentheses print( 5 * 8 - 2 ) -- space math local ply_meta = FindMetaTable( "Player" ) -- metatables suffixed with _meta -- obtains the size of the player's buttocks function ply_meta:GetCheekSize() return self.cheek1 + self.cheek2 end -- sets the size of the player's buttocks function ply_meta:SetCheekSize( x ) local mat = hardwarestore.buy( "Paint Thinner" ) local theneedle = needle( mat, x ) self:Inject( theneedle ) end -- ????????? local i = util.Stack() i:Top() i:Push( "shit" ) i:Pop() [/CODE][/QUOTE] kys asap plz [highlight](User was banned for this post ("Why reply" - Reagy))[/highlight]
[QUOTE=Rocket;52100153]In some sort of hypothetical Clojure-like dialect of Lisp that worked with Garry's Mod functions and libraries: [code] (hook.Add "Init" "PrintIdiot" (fn [] (do (def idiot LocalPlayer) (if (= (idiot:Name) "Wavie") (print (.. (idiot:Name) " is an idiot.") (print (.. (idiot:Name) " is cool."))))))) [/code][/QUOTE] I believe Racket bad a sort of similar functional approach. But my original example was out of jest since I believe Lisp is an eyesore of a language.
some indentation from me r8 me: [CODE] shit = {} -- always create a "container" for all shit you make local function shit.shit( arg1, arg2, arg3 ) -- add spaces to parentheses if there are >1 args local var = 1 -- indent with tabs local var2, var3 = shit.getVar2and3() -- camelCase also --try to place to top as much vars as possible, it would help --also add blank lines between each segment (vars, logic, returns and so on) of code so it's easier to read it for _, ply in pairs(player.GetAll()) do -- loose unneeded vars names in "for" loop and give friendly names to needed ones --stuff happens if stuff and ( stuff2 or stuff3 ) then-- only add parentheses where you need them shit.doShit() else shit.doOtherShit() end if stuff2 and stuff3 then return false end -- sometimes i use one-lined IFs as they save lots of space end return shit end [/CODE]
[QUOTE=Rocket;52100268]Of all the indentation styles, you pick two spaces?[/QUOTE] And out of all the styles you choose tabs? You're despicable.
[QUOTE=txike;52100274]And out of all the styles you choose tabs? You're despicable.[/QUOTE] Tabs for indention, spaces for alignment, purge the heretics, cyber war now
[QUOTE=Apickx;52100293]Tabs for indention, spaces for alignment, purge the heretics, cyber war now[/QUOTE] I agree but I can't really bring myself to care anymore. As long as your editor auto-detects the style used by whatever you're editing you should be fine.
Lots of whitespace; used primarily to seperate between different "concepts" of what you're doing. eg. [code] int = 1 int = 2 int = 3 function( racism ) do goteem end [/code] i also space everything I can in between brackets (except certain things) "beautiful code" is only really beautiful because it makes it much easier for other people to look at it and understand it. thats why another thing that is SO important is making sure you have documentation for EVERYTHING (comments, multi-line comments, the whole 10 yards). some might disagree though, and say that beautiful code is actually code that accomplishes the same thing with less amounts of code (eg. doing a for loop instead of 10 if then statements); in which i would agree with them. that's also a huge part of it in conclusion, i think optimized, well spaced (and formatted) code, along with documentation to back it up, makes "beautiful" code
[code]<script>alert("xss")</script>[/code]
• consistent casing and naming conventions for functions and variables • return early to avoid long if-else chains congrats, your code is now pretty
Sorry, you need to Log In to post a reply to this thread.