Tips for golfing in Lua
Printing
There are two ways to print in Lua. print adds a newline to the end, while io.write does not.
load
load is useful in many cases:
-- replace a repeated code segment:
load(("…"):gsub("…","…"))()
-- split a string:
s="1,2,3,4,5,6,7,8,9"
load("a={"..s.."}")()
-- iterate over a string
s="abc123"
s:gsub(".",load"…")
Note that load returns a function, rather than just running the code within.
Falsy values
Unlike many other programming languages like Python and C, 0 is not a falsy value in Lua (it is treated as true). The only values considered falsy are the literal false, and nil. nil is the default value for any undeclared variable, which is very flexible in combination with and/or ternaries.
Other tips
- Functions with a single string argument can be called without parentheses, e.g.
print"…".
- If you need a function multiple times, assign it to a shorter variable.
- Use
("").… instead of string.… (s.… saves more if s is a predefined string variable).
- Use colon call syntax when possible for string methods, e.g.
s:gsub(…) instead of s.gsub(s,…).
- Strings delimited by
[[ and ]] can contain unescaped newlines.
- Try to replace
if with and/or ternaries.
- Use
... for holes with only a single argument, or within load functions to access arguments.
- Literal array indexing is often a shorter alternative to
if statements and ternaries, e.g. b=({1,2})[a]. Keep in mind, however, that Lua arrays are 1-indexed.
- The
^ (power) operator always returns a float value, which causes print to output a decimal point. If you intend to print the output without the decimal, you will either have to floor it or use io.write instead. Note that the floor division operator // will not convert floats into integers, but bitwise operations often will.
- If you need an empty(ish) table, you can recycle any of
io, os, or _G instead of declaring your own.