LunaLua style guide

From Moondust Wiki
Revision as of 22:16, 17 April 2018 by The0x539 (talk | contribs) (→‎Syntax Elements: this one goes out to you, rocky)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

This document covers mostly code formatting, rather than programming practices.

Whitespace

function foo(x, y) -- Spaces between arguments
	-- Indent with tabs. Comments should match indentation.
	local myVar    = 1 --Optionally align. If aligning, use spaces, in case tab width/behavior differs for someone else.
	local otherVar = 2

	local someTbl = {
		"Tables split across",
		"multiple lines should",
		"look like this."
	}
	print(#someTbl)    -- No spaces after unary operators.
	print(not someTbl) -- (except the 'not' unary operator)
	print(x + myVar)   -- Spaces between binary operators.
	return x*x + y*y   -- (optionally, except when it's the cleanest looking way to clarify order of operations in an expression)
	                   -- Optionally, align comments when they're related and improves readability. Like with alignment of
	                   -- assignments, use spaces after the current indentation level.
end

do
	-- Indent the contents of do-end blocks.
end

Syntax Elements

local x = "Single-line strings should use double quotes."
-- Semicolons are discouraged.
-- If using semicolons in a code file, use consistently throughout entire file.
print("Use parentheses when calling functions using string literals.")
-- Should the require function become common in LunaLua, it is a possible exception to the above rule.
x = doSomething{ --No space here
	someParameter = "Do not use parentheses",
	otherParameter = "when calling functions using a named argument table."
}
if simpleCondition then
	-- If the condition is simple (subjective), do not use parentheses
end
if (usingParentheses) then
	-- Put a single space on either side of condition, whether or not parentheses are present
end

Comments

--------------------
-- SECTION HEADER --
--------------------

-- Prose comments on their own line should have a space after the --.
local x --This is optional for end-of-line comments, though these should always have space before the --.
-- Multi-line comments should generally still use line comment syntax

--- LDoc-compatible function description.
-- Optional additional description lines.
-- @param foo first parameter
-- @param bar second parameter
function doAThing(foo, bar)
	return foo + bar
end

LunaLua

Library layout

  • Table declaration
  • Load dependencies
  • Private/exposed variables
    • Private variables going first is preferred.
  • Private/exposed functions
    • Private functions going first is preferred.
  • onInitAPI event handler
  • Other event handlers, ordered by event loop ordering (first global, then per-NPC, for each event)
  • Return statement