I don't know about you guys, but I don't always find it necessary to comment and document certain things if to me they're self explanatory.
Also I always write code assuming that it will always be used properly, so I don't usually do null checking or anything unless I know it's possible for something to be null. Like handling entities.
I personally like the following style:
lowerCamelCase for variable names
UpperCamelCase for function names
_lowerCamelCase for implementation variables that shouldn't be modified (eg something that you should use a getter or a setter on a meta table to access)
CAPS_WITH_UNDERSCORES for constants (well variables that I never change... so as close as you can get for constants)
[B]All that really matters is this: MAKE SURE YOU HAVE A FORMAT[/B]
It doesn't really matter what your format is (though if it's mine it's the right one <3) but make sure you have one and make sure it allows you to tell what purpose a variable plays without having to find where the variable is assigned. You should be able to look at a variable and say oh that's a value or oh that's a function.
You should also have naming rules like all functions that check something and return a boolean are prefixed with Is eg: IsMyFormatCool( format )? or for something that inits an object always start with Init or Make or Setup but ALWAYS USE THE SAME THING don't switch around throughout your code.
For methods that are internal make sure you denote that with how you name them. Use an _ or something like that to suggest that yes, you can see this and it is exposed, but really it's not something you're ment to call or i woulda made the name more natural.
Just use consistant naming so when someone else takes a look at your code they can figure out what your rules are and can make sense of your code.
(I only write such a long rant because right now I'm helping a friend who's trying to fix up a project written entirely in E2 capitalized format)
EDIT: EvacX and I use exactly the same formatting rules apparently :)
[QUOTE=Walrus Viking;44868396]I don't know about you guys, but I don't always find it necessary to comment and document certain things if to me they're self explanatory.[/QUOTE]
Well yeah, but you're missing the point. I write my code as if someone else has to use it, and sometimes that's even the case. The generated documentation is an easy way to look-up which functions are available to you and it helps expressing the bigger picture.
If you look at my example, sure, it's all fairly self-explanatory, it's a math library after all. The shown documentation is not nearly as beneficial as it can be in other situations. I just chose that exact example because it didn't require any prior knowledge to understand what was going on, it's just math.
Oh, and the generated pages look cool.
Since I'm using simploo a lot nowadays I had to force myself to a consistent coding style otherwise things would have gotten messy.
You should be able to figure it out for yourself by looking at it.
[URL="https://gist.github.com/LennyPenny/a7bcb8577e26268dfffc"]gist[/URL]
(semi colons are there because simploo uses tables, so I could also use things like commas, but semi colons seemed more appropriate. I don't use them in code that doesn't require them)
I like spaces
[code]
-- This function handles players opening crates.
function TGC.HandlePlayerOpening( ply, crate )
if ( not ply:IsPlayer() ) or ( not ply:Alive() ) or ( not IsValid( crate ) ) then return end
local timerName = tostring(ply) .. tostring(crate);
local endTime = CurTime() + TGC.UncratingTime;
if ( timer.Exists( timerName ) ) then return end
-- Freeze, send and create a timer.
ply:Freeze( true );
TGC.SendCrateTime( ply, CurTime(), endTime );
timer.Create( timerName, TGC.UncratingTime, 1, function()
if ( not IsValid( ply ) ) then return end -- Check for validity of player.
ply:Freeze( false ); -- Unfreeze the player PLEASE.
TGC.HandleUncrating( ply, crate );
end )
end
[/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]
Didn't seem to break numbering for me...
[QUOTE=DropDeadTed;44870492]Didn't seem to break numbering for me...[/QUOTE]
[ERROR] lua/autorun/syntaxTest.lua:6: hi
1. error - [C]:-1
2. unknown - lua/autorun/syntaxTest.lua:6
[code]
/*
a
a
a
*/
error"test"
[/code]
Edit: Turns out the issue is when a blank line is within the multi-line c-style comment.
I like semicolons.
Fight me.
Ever since I got into gLua I always forget to put semicolons in my PHP scripts. Fuck you Lua.
[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]
All the time I've scripted in Garry's Mod and I just now find this out. Oh god.
i love lowercases so i commonly use lowecase functions and variables
I close all ifs, fors, table brackets, argument parentheses etc. the moment they are created and then backtrack and insert stuff from there.
Im pretty hated for not using using spaces in my codes.
[lua]
if(SERVER) then
WH_ORDERS = {}
local meta = FindMetaTable("Player")
function SetOrder(ply, pos, type)
local c = tonumber(team.NumPlayers(3))
if(c > 0) then
if(#WH_ORDERS > 2) then
table.Empty(WH_ORDERS)
for k,v in pairs(player.GetAll()) do
if(v) then
if(v:IsPlayer()) then
if(v:IsValid()) then
if(v:Team() == 3) then
v:GetWorders()
end
end
end
end
end
end
--
table.insert(WH_ORDERS, {p = ply, pos = pos, t = type})
for k,v in pairs(player.GetAll()) do
if(v) then
if(v:IsPlayer()) then
if(v:IsValid()) then
if(v:Team() == 3) then
v:GetWorders()
if!(v == ply) then
v:ChatPrint("You've Got New Orders From " .. ply:Nick() .. "!", Color(200,2,2))
end
end
end
end
end
end
ply:ChatPrint("You've Sent the Orders to The Other Wehrmacht Soldiers", Color(28,643,123))
else
ply:ChatPrint("There Are No Soldiers But You.", Color(255,0,0))
end
end
[/lua]
but Sublime Text 2 Forces me to use spaces :(
(I usally use Notepad++)
[QUOTE=SweetTea;44876413]Im pretty hated for not using using spaces in my codes.
[lua]
for k,v in pairs(player.GetAll()) do
if(v) then
if(v:IsPlayer()) then
if(v:IsValid()) then
if(v:Team() == 3) then
v:GetWorders()
if!(v == ply) then
v:ChatPrint("You've Got New Orders From " .. ply:Nick() .. "!", Color(200,2,2))
end
end
end
end
end
end
ply:ChatPrint("You've Sent the Orders to The Other Wehrmacht Soldiers", Color(28,643,123))
else
ply:ChatPrint("There Are No Soldiers But You.", Color(255,0,0))
end
end
[/lua]
[/QUOTE]
Even with no spaces, that's just terrible coding...
[lua]
for k,v in pairs(player.GetAll()) do
if IsValid(v) and v:Team() == 3 then
v:GetWorders()
if !(v == ply) then
v:ChatPrint("You've Got New Orders From " .. ply:Nick() .. "!", Color(200,2,2))
end
ply:ChatPrint("You've Sent the Orders to The Other Wehrmacht Soldiers", Color(28,643,123))
else
ply:ChatPrint("There Are No Soldiers But You.", Color(255,0,0))
end
end
[/lua]
You don't need a bajillon if statements to check for things that cannot happen, as well as seperating them for no reason...
Also your logic is terrible and it doesn't work properly but I didn't bother to fix that.
[QUOTE=SweetTea;44876413]Im pretty hated for not using using spaces in my codes.
[lua]
if(SERVER) then
WH_ORDERS = {}
local meta = FindMetaTable("Player")
function SetOrder(ply, pos, type)
local c = tonumber(team.NumPlayers(3))
if(c > 0) then
if(#WH_ORDERS > 2) then
table.Empty(WH_ORDERS)
for k,v in pairs(player.GetAll()) do
if(v) then
if(v:IsPlayer()) then
if(v:IsValid()) then
if(v:Team() == 3) then
v:GetWorders()
end
end
end
end
end
end
--
table.insert(WH_ORDERS, {p = ply, pos = pos, t = type})
for k,v in pairs(player.GetAll()) do
if(v) then
if(v:IsPlayer()) then
if(v:IsValid()) then
if(v:Team() == 3) then
v:GetWorders()
if!(v == ply) then
v:ChatPrint("You've Got New Orders From " .. ply:Nick() .. "!", Color(200,2,2))
end
end
end
end
end
end
ply:ChatPrint("You've Sent the Orders to The Other Wehrmacht Soldiers", Color(28,643,123))
else
ply:ChatPrint("There Are No Soldiers But You.", Color(255,0,0))
end
end
[/lua]
but Sublime Text 2 Forces me to use spaces :(
(I usally use Notepad++)[/QUOTE]
Oh my god :suicide:
That is just so bad, for so many reasons.
[QUOTE=AnonTakesOver;44876487]Oh my god :suicide:
That is just so bad, for so many reasons.[/QUOTE]
I never expected that people would start a discussion about a 3 years old code i found in a former gamemode. Seriously.
[editline]22nd May 2014[/editline]
[QUOTE=OzymandiasJ;44876451]Even with no spaces, that's just terrible coding...
[lua]
for k,v in pairs(player.GetAll()) do
if IsValid(v) and v:Team() == 3 then
v:GetWorders()
if !(v == ply) then
v:ChatPrint("You've Got New Orders From " .. ply:Nick() .. "!", Color(200,2,2))
end
ply:ChatPrint("You've Sent the Orders to The Other Wehrmacht Soldiers", Color(28,643,123))
else
ply:ChatPrint("There Are No Soldiers But You.", Color(255,0,0))
end
end
[/lua]
You don't need a bajillon if statements to check for things that cannot happen, as well as seperating them for no reason...
Also your logic is terrible and it doesn't work properly but I didn't bother to fix that.[/QUOTE]
You don't need thousends of if's but i used to code it like that because it was easier to organize the 'ifs'.
[QUOTE=SweetTea;44876601]I never expected that people would start a discussion about a 3 years old code i found in a former gamemode. Seriously.
[editline]22nd May 2014[/editline]
You don't need thousends of if's but i used to code it like that because it was easier to organize the 'ifs'.[/QUOTE]
You need to format. I had a difficult time finding the end of that 2nd if statement just bc I usually count indention's to get to it quickly. I hope you have at least advanced a little bit in the past 3 years.
[lua]for k,v in pairs(player.GetAll()) do
if IsValid(v) and v:Team() == 3 then
v:GetWorders()
if !(v == ply) then
v:ChatPrint("You've Got New Orders From " .. ply:Nick() .. "!", Color(200,2,2))
end
ply:ChatPrint("You've Sent the Orders to The Other Wehrmacht Soldiers", Color(28,643,123))
else
ply:ChatPrint("There Are No Soldiers But You.", Color(255,0,0))
end
end[/lua]
[QUOTE=SweetTea;44876601]I never expected that people would start a discussion about a 3 years old code i found in a former gamemode. Seriously.
[editline]22nd May 2014[/editline]
You don't need thousends of if's but i used to code it like that because it was easier to organize the 'ifs'.[/QUOTE]
Show something you've made recently.
[LUA]
local local_variable_with_spaces = true
local variable = true
GLOBAL_VARIABLE = true
local MyTable = { ["key"] = value }
local function AllPlayers() end
function Context_AllPlayers() -- where context is whatever addon im working with that requires a global func
for _, ply in pairs( player.GetAll() ) do
if ply:Nick():len() > 10 and not MyTable[ply:SteamID()] then
print( ply:Nick() )
end
end
end
[/LUA]
- no semicolons
- spaces in functions and tables, unless no args/entries
- spaces to make things more readable
- newlines are nice, but i used to overuse them and now they scare me
- tabs for each new line in same scope
- no C operators
works for me
I usually program in Java and am a tidy motherfucker...except when it comes to Ternary operators. It's a fucking challenge and I love nesting them.
[code] public static int average(int i, int j) {
return ((i / 2) + (j / 2))
+ ((i % 2 == 1) && (j % 2 == 1) ? 1 : (i % 2 == -1
&& j % 2 == -1 ? -1 : 0));
}[/code]
Onto something more realistic -- the purpose of a Ternary is to confuse the fuck out of people and write intense one-liner functions. [I]So how can you justify not using brackets with an if statement?[/I] You're going to murder someone someday because you don't.
[U]You're not a magician, wrap your condition.[/U]
[editline]22nd May 2014[/editline]
Sudden realization: this isn't the programming subforum. Java still accepted? :v:
[QUOTE=Mors Quaedam;44863077]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[/QUOTE]
WTF you code the same way as me................
This is far from an example of easily understandable code, but it does show how I like to lay it out.
I like to stick to traditional Lua syntax (semicolons not included) and have new lines before/after control structures where the indentation level is not changing.
All variables are camelCase, with table members / functions being UpperCamelCase (the p function is an exception).
I also love to just throw newlines in wherever they make code prettier.
Feel free to use this code, it's pretty useful if you like to execute Lua on your server(s) often.
[code]
--[[
p"Willox":Kill()
p"*":Kill()
local steamid = p"skooch":SteamID()
Will return last result after calling method on all matching players
]]
local function MetaCallIterator(func, objects)
return function(_, ...)
for k, obj in ipairs(objects) do
if k == #objects then
return func(obj, ...)
else
func(obj, ...)
end
end
end
end
local plyMeta = FindMetaTable("Player")
local pMeta = {}
pMeta.__index = function(self, key)
local func = plyMeta.__index({}, key) -- This will also check the Entity metatable
if type(func) == "function" then
return MetaCallIterator(func, self.Players)
end
end
function p(name)
local obj = {}
if name == "*" then
obj.Players = player.GetAll()
else
obj.Players = {}
for _, ply in pairs(player.GetAll()) do
if string.find(string.lower(ply:Nick()), string.lower(name), nil, true) then
table.insert(obj.Players, ply)
end
end
end
setmetatable(obj, pMeta)
return obj
end
[/code]
[url]https://gist.github.com/wiox/91ec0cdd8bc1524cdf53[/url] (prettier highlighting)
That looks like it overrides the index function globally for all players. That sounds like a recipe for serious slow downs...
[QUOTE=thelastpenguin;44879092]That looks like it overrides the index function globally for all players. That sounds like a recipe for serious slow downs...[/QUOTE]
Nah, pMeta is a metatable I am creating in that script (the names are a little similar, sorry). It does call the Player metatable's __index metamethod, but that's just to avoid having to check the Entity metatable as well. It shouldn't affect the speed of any current code at all.
[code]local func = plyMeta.__index({}, key)[/code] is the most hilarious line I recall ever writing.
But basically the script allows you to p(player_name):Kill() (or any other method player's have) and have it affect multiple players. Using some nifty Lua syntax stuff you can just p"PlayerName":Kill().
woah that looks hip as fuck, need to use that for everything now
[QUOTE=Mors Quaedam;44863077]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[/QUOTE]
The lazy style, you guys should add spaces at least after the commas and the concatenation operator (double dots), it's terrible to read :pwn:.
[QUOTE=Zignd;44880301]The lazy style, you guys should add spaces at least after the commas and the concatenation operator (double dots), it's terrible to read :pwn:.[/QUOTE]
Hm, I always found it easier to read like it is there. I guess those are just small coding variations (to space, or not to space)
At least most of us don't use [URL="https://dl.dropboxusercontent.com/u/26074909/tutoring/_tutorial_quizzes/_coding_standards.lua.html"]_this; __coding; ___style;[/URL]
[QUOTE=Mors Quaedam;44880357]Hm, I always found it easier to read like it is there. I guess those are just small coding variations (to space, or not to space)
At least most of us don't use [URL="https://dl.dropboxusercontent.com/u/26074909/tutoring/_tutorial_quizzes/_coding_standards.lua.html"]_this; __coding; ___style;[/URL][/QUOTE]
Ohh God, that's space abuse. When it comes to spaces I usually use the most common code spacing pattern.
[code]
function Zignd.FooBar(foo, bar)
MsgN("Player " .. tostring(foo) .. " killed " .. tostring(bar))
end
[/code]
Some people may not like my style, but:
[code]
local lowerCamelCase = "for variables" // Makes them more readable than any other option
function UpperCamelCase() end // For functions, etc, except for one word functions
render.Something( "spaces", "between", 10, "arguments", "string " .. "con" .. " cat" ) // Makes the code more readable than
render.Something("spaces","between",10,"arguments","string ".."con".." cat") // On a bigger scale
[/code]
No semicolons
C style comments and operators. Yes, Lua's comments may be more functional, but C comments are just easier to write with numpad.
C style operatons because most languages use && || over and/or, and they are shorter, and easier to type. I occasinally use "or" too.
No underscores before names. _ for useless variables.
Always add parenthesis for all ifs, to make code consistent, even though they are not required.
Tab is 4 spaces, normal tabulation before code, no tabulation between "=" and variables.
I don't usually comment my code too much. And then I pay the price :v:
For C style functions/ifs
[code]
int function something() { // Always put the { here, no need to waste a line on it
}
if ( someCondition ) {
// Do shit
} else {
// Do something else
}
[/code]
Sorry, you need to Log In to post a reply to this thread.