This manual is a work-in-progress guide for code-golfing in Lua. It assumes you're already proficient with the language.
These practices usually make code shorter. Do these if applicable, and of course, only if shorter.
This should go without saying, but minimize whitespace (spaces, tabs, newlines). More in Omit whitespace.
-- instead of:
while true do
if (...) then
(...)
else
(...)
end
end
-- do this:
while true do if (...) then (...) else (...) end end
-- or even this:
while''do if (...) then (...) else (...) end end
Lua can parse multiple statements on one line without a semicolon. Taking advantage of omitting whitespace, this can chop a character or two.
-- instead of:
print('this')
print('that')
-- do this:
print('this') print('that')
-- or even this:
print('this')print('that')
-- instead of:
local x=1
-- do this:
x=1
Rename functions to one-letter variables.
-- instead of:
print('this')print('that')print('those')
-- do this:
p=print p('this')p('that')p('those')
-- instead of:
print('this')print('that')print('those')
-- do this:
p=print p'this'p'that'p'those'
Many tokens don't need whitespaces after them to seperate them from others. Here is a list;
(
,)
{
,}
[
,]
'
,"
...
...and there are these ones, but you probably know them already; #
, %
, &
, *
, +
, ,
, -
, .
, ..
, /
, //
, :
, <
, <=
, =
, ==
, >
, >=
, ^
, |
, ~
, ~=
.
-- instead of:
if y then print ('yes') else print ('no') end
-- or:
if y then print('yes') else print('no') end
-- do this:
if y then print('yes')else print('no')end
-- ^^ ^^
-- Notice how there's no whitespace.
-- or even this:
if y then print'yes'else print'no'end
Use an and
/or
ternary expression instead of an if
statement.
-- instead of:
if x then a=y else a=z end
-- do this:
a=x and y or z
- any number, including 0
- empty string
- empty table
- nil (a.k.a. undeclared variable)
while''do
while""do
while{}do (...) end