A guide to golfing in Lua

Tags: luatechnology

Code golfing is a form of recreational programming. The solutions are esoteric, hard to read and reason about, sometimes inefficient, unmaintainable and inflexible. And still, when you manage to reduce the length of your code, you feel like a genius. It requires you to think outside the box and to take programming languages to their limits.

Lua is a fun language to play Code Golf. Despite its small size (it's one of the smallest compiler / interpreter that you can use to play in code.golf), it's surprisingly powerful for common golfing problems.

Here are some tips to keep in mind when golfing in Lua.

Remove whitespace

Pretty self explanatory, remove whitespace where possible. This is usually the last thing I do.

Variable and function names

Another obvious one. If you use a function a lot, It's good to assign it to a shorter name.

Get rid of parentheses

If you are calling a function with a single string or table literal as arguments you can omit them.


Don't use if

Sometimes you don't need if then else. You can use and and or as a ternary expression.

y = 6
if y == 5 then
x = 4
x = 2

-- Much shorter!
x = y == 5 and 4 or 2

Something to keep in mind is that the first value (4 in the example above) cannot be false nor nil.

Use load()

This function is a powerful one, as you can generate code and execute it on the fly. There are many uses cases for it. Combining it with Lua's string functions is advised.

-- Convert a string containing
-- space-separated numbers into a table.

numbers = "10 20 -39 4.34 34e2"

t = load("return {" .. numbers:gsub(" ", ",") .. "}")()

You can also use load as a short way of creating anonymous functions with no arguments.

function add()return 4+5 end

add=load"return 4+5"

String methods and patterns

Lua has many interesting and useful methods for working with strings. Remember to use the method call syntax to shorten your code.

text = "hello world"
print(string.upper(text)) -- Bad
print(text:upper())       -- Better

You don't need ipairs

It's better to use a regular for loop, you save a few characters.

t = {1, 2, 3, 4, 5}

for i,x in ipairs(t)do print(x)end

for i=1,#t do print(t[i])end

Parsing numbers

Converting strings to numbers is a common problem when parsing command line arguments. Instead of tonumber(), just use +0.

input = "190"
a = tonumber(input)
b = input+0
c = input|0

Use tables as a switch statement

n = 9
if n % 2 == 0 then

print(({"even", "odd"})[n % 2 + 1])

Use the global table

Instead of

T = {}
T.x = 5

You can use _G, the global table.

_G.x = 5

Of course, this is just an incomplete list, despite its small size, Lua has many more features that I didn't cover.

Happy golfing!