The snippets are under the CC-BY-SA license.

Creative Commons Attribution-ShareAlike 3.0

Logo

Programming-Idioms.org

  • The snippets are under the CC-BY-SA license.
  • Please consider keeping a bookmark
  • (instead of printing)
Lua
1
Print a literal string on standard output
print("Hello World")
2
Loop to execute some code a constant number of times
for i=1, 10 do
	print('Hello')
end
Alternative implementation:
print(("Hello\n"):rep(10))
Alternative implementation:
print(string.rep("Hello\n", 10))
Alternative implementation:
local i = 0
repeat
	i = i + 1
	print("Hello")
until i == 10
3
Like a function which doesn't return any value, thus has only side effects (e.g. Print to standard output)
function finish(name)
	print('My job here is done. Goodbye, '..name..'.')
end
4
Create a function which returns the square of an integer
function square(x)
	return x*x
end
5
Declare a container type for two floating-point numbers x and y
point = { x = 123, y = 456 }
6
Do something with each item x of the list (or array) items, regardless indexes.
for _, x in ipairs(items) do
	print(x)
end
7
Print each index i with its value x from an array-like collection items
for i, x in ipairs(items) do
	print('Index: '..i..', Value: '..x)
end
8
Create a new map object x, and provide some (key, value) pairs as initial content.
x = {one = 1, two = 2}
9
The structure must be recursive because left child and right child are binary trees too. A node has access to children nodes, but not to its parent.
local function BinTree(v, l, r)
	return {
		val = v,
		left = l,
		right = r
	}
end
10
Generate a random permutation of the elements of list x
shuffled = {}
for i, v in ipairs(x) do
	local pos = math.random(1, #shuffled+1)
	table.insert(shuffled, pos, v)
end
Alternative implementation:
function(x)
	for i = #x, 2, -1 do
		local j = math.random(i)
		x[i], x[j] = x[j], x[i]
	end
end
11
The list x must be non-empty.
x[math.random(#x)]
12
Check if the list contains the value x.
list is an iterable finite container.
function contains(list, x)
	for _, v in pairs(list) do
		if v == x then return true end
	end
	return false
end
13
Access each key k with its value x from an associative array mymap, and print them.
for k, x in pairs(mymap) do
	print('Key: '..k..', Value: '..x)
end
14
Pick a random number greater than or equals to a, strictly inferior to b. Precondition : a < b.
function pick(a,b)
	return a + (math.random()*(b-a))
end
15
Pick a random integer greater than or equals to a, inferior or equals to b. Precondition : a < b.
math.random(a, b)
16
Call a function f on every node of binary tree bt, in depth-first infix order
local function dfs(bt, f, ...)
  local tt = type(bt)
  if tt~='table' and tt~='userdata' then return end
  dfs(t.left, f, ...)
  f(t.data, ...)
  dfs(t.right, f, ...)
end
17
The structure must be recursive. A node may have zero or more children. A node has access to its children nodes, but not to its parent.
local function Tree(v, c)
	return {
		val = v,
		children = c
	}
end
19
Reverse the order of the elements of the list x.
This may reverse "in-place" and destroy the original ordering.
rev = {}
for i=#x, 1, -1 do
	rev[#rev+1] = x[i]
end
x = rev
Alternative implementation:
rev = {}
for i=#x, 1, -1 do
	rev[#rev+1] = x[i]
end

-- in-situ reversal
function reverse(t)
  local n = #t
  local i = 1
  for i = 1, n do
    t[i],t[n] = t[n],t[i]

    n = n - 1
  end
end
Alternative implementation:
function array_reverse(x)
  local n, m = #x, #x/2
  for i=1, m do
    x[i], x[n-i+1] = x[n-i+1], x[i]
  end
  return x
end
20
Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.
function search(m, x)
   for i,v1 in ipairs(m) do
      for j,v2 in ipairs(v1) do
         if v2 == x then return i,j end
      end
   end
end
21
Swap the values of the variables a and b
a, b = b, a
22
Extract the integer value i from its string representation s (in radix 10)
i = tonumber(s)
23
Given a real number x, create its string representation s with 2 decimal digits following the dot.
s = string.format("%.2f",x)
24
Declare a new string s and initialize it with the literal value "ネコ" (which means "cat" in japanese)
s = 'ネコ'
26
Declare and initialize a matrix x having m rows and n columns, containing real numbers.
local x = setmetatable({},{
   __index = function(t1,k1)
      t1[k1] = setmetatable({},{
         __index = function(t2,k2)
            t2[k2] = 0
            return t2[k2]
         end
      })
      return t1[k1]
   end
})
Alternative implementation:
x = {}
for i=1,m do
  x[i] = {}
  for j=1,n do
    x[i][j] = 0
  end
end
27
Declare and initialize a 3D array x, having dimensions boundaries m, n, p, and containing real numbers.
local x = {}
for i=1,m do
   x[i] = {}
   for j=1,n do
      x[i][j] = {}
      for k=1,p do
         x[i][j][k] = 0
      end
   end
end
28
Sort the elements of the list (or array-like collection) items in ascending order of x.p, where p is a field of the type Item of the objects in items.
table.sort(items, function(a,b)
	if a.p < b.p then return true end
end)
29
Remove i-th item from list items.
This will alter the original list or return a new list, depending on which is more idiomatic.
Note that in most languages, the smallest valid value for i is 0.
local removedItem = table.remove(items,i)
31
Create the recursive function f which returns the factorial of the non-negative integer i, calculated from f(i-1)
function f(n)
   local function f_(factorial,n)
      if n < 2 then return 1
      return f_(factorial*n, n-1)
   end
   return f_(1,n)
end
32
Create function exp which calculates (fast) the value x power n.
x and n are non-negative integers.
function exp(x, n)
    return x^n
end
35
Implement a function compose (A -> C) with parameters f (A -> B) and g (B -> C), which returns the composition function g ∘ f
function compose(f,g)
   return function(x)
      return g(f(x))
   end
end
36
Implement a function compose which returns composition function g ∘ f for any functions f and g having exactly 1 parameter.
function compose(f,g)
   return function(x)
      return g(f(x))
   end
end
37
Transform a function that takes multiple arguments into a function for which some of the arguments are preset.
function curry2(f)
   return function(a)
      return function(b)
         return f(a,b)
      end
   end
end

function add(a,b)
   return a + b
end

local curryAdd = curry2(add)
local add2 = curryAdd(2)
Alternative implementation:
local unpack = unpack or table.unpack
local function aux_ncurry(n, m, fn, args)
  if m>n then return fn(unpack(args,1,n))end
  local new_args, new_m = {}, m
  for i=1,m-1 do new_args[i]=args[i]end
  return function(a) 
    new_args[new_m]=a
    return aux_ncurry(n, new_m + 1, fn, new_args)
  end
end
local function ncurry(n, fn) return aux_ncurry(n,1,fn,{}) end
38
Find substring t consisting in characters i (included) to j (excluded) of string s.
Character indices start at 0 unless specified otherwise.
Make sure that multibyte characters are properly handled.
local t = s:sub(i, j - 1)
39
Set the boolean ok to true if the string word is contained in string s as a substring, or to false otherwise.
ok = s:find(word, 1, true)
Alternative implementation:
ok = false
if s:find(word, 1, true) then ok = true end
Alternative implementation:
ok = s:find(word, 1, true) ~= nil
41
Create string t containing the same characters as string s, in reverse order.
Original string s must remain unaltered. Each character must be handled correctly regardless its number of bytes in memory.
function utf8.reverse(s)
	local r = ""
	for p,c in utf8.codes(s) do
		r = utf8.char(c)..r
	end
	return r
end

t = utf8.reverse(s)
43
Look for a negative value v in 2D integer matrix m. Print it and stop searching.
breakout = false
for i,v1 in ipairs(m) do
   for j,v2 in ipairs(v1) do
      if v2 < 0 then
         print(v2)
         state = "found"
         breakout = true
         break
      end
   end
   if breakout then break end
end
44
Insert the element x at position i in the list s. Further elements must be shifted to the right.
table.insert(s,i,x)
45
Sleep for 5 seconds in current thread, before proceeding with the next instructions.
local start = os.clock()
while os.clock() - start < 5 do end
Alternative implementation:
os.execute(package.config:sub(1,1) == "/" and "sleep 5" or "timeout 5")
46
Create string t consisting of the 5 first characters of string s.
Make sure that multibyte characters are properly handled.
t = s:sub(1,5)
48
Assign to variable s a string literal consisting in several lines of text, including newlines.
s = [[
Huey
Dewey
Louie
]]
Alternative implementation:
s = 'Huey \n'..
'Dewey \n'..
'Louie'
49
Build list chunks consisting in substrings of the string s, separated by one or more space characters.
chunks = {}
for substring in s:gmatch("%S+") do
   table.insert(chunks, substring)
end
50
Write a loop that has no end clause.
while true do 
	-- Do something
end
51
Determine whether the map m contains an entry for the key k
m[k] ~= nil
53
Concatenate elements of string list x joined by the separator ", " to create a single string y.
y = table.concat(x, ", ")
54
Calculate the sum s of the integer list or array x.
s = 0
for i,v in ipairs(x) do
   s = s + v
end
55
Create the string representation s (in radix 10) of the integer value i.
s = tostring(i)
57
Create the list y containing the items from the list x that satisfy the predicate p. Respect the original ordering. Don't modify x in-place.
y = {}
for _, v in ipairs(x) do
	if p(v) then y[#y+1] = v end
end
58
Create string lines from the content of the file with filename f.
lines = io.input(f):read('a')
59
Print the message "x is negative" to standard error (stderr), with integer x value substitution (e.g. "-2 is negative").
io.stderr:write(string.format("%d is negative\n",x))
60
Assign to x the string value of the first command line parameter, after the program name.
x = arg[1]
61
Assign to the variable d the current date/time value, in the most standard type.
d = os.date()
62
Set i to the first position of string y inside string x, if exists.

Specify if i should be regarded as a character index or as a byte index.

Explain the behavior when y is not contained in x.
i = x:find(y)
63
Assign to x2 the value of string x with all occurrences of y replaced by z.
Assume occurrences of y are not overlapping.
x2 = x:gsub(y,z)
65
From the real value x in [0,1], create its percentage string representation s with one digit after decimal point. E.g. 0.15625 -> "15.6%"
s = string.format("%.1f%%", x*100)
69
Use seed s to initialize a random generator.

If s is constant, the generator output will be the same each time the program runs. If s is based on the current value of the system clock, the generator output will be different each time.
math.randomseed(s)
70
Get the current datetime and provide it as a seed to a random generator. The generator sequence will be different at each run.
math.randomseed( os.time() )
71
Basic implementation of the Echo program: Print all arguments except the program name, separated by space, followed by newline.
The idiom demonstrates how to skip the first argument if necessary, concatenate arguments as strings, append newline and print it to stdout.
print( table.concat( arg, " " ) )
74
Compute the greatest common divisor x of big integers a and b. Use an integer type able to handle huge numbers.
function gcd(x, y)
	if (y == 0) then
		return x
	else 
		return gcd(y, x%y)
	end
end
Alternative implementation:
function gcd(a, b)
	return b==0 and a or gcd(b,a%b)
end
76
Create the string s of integer x written in base 2.

E.g. 13 -> "1101"
local s = {}

while x > 0 do
    local tmp = math.fmod(x,2)
    s[#s+1] = tmp
    x=(x-tmp)/2
end

s=table.concat(s)
78
Execute a block once, then execute it again as long as boolean condition c is true.
repeat
	someThing()
	someOtherThing()
until not c
79
Declare the floating point number y and initialize it with the value of the integer x .
y = x + .0
Alternative implementation:
y = (16 ^ 13) + x - (16 ^ 13)
80
Declare integer y and initialize it with the value of floating point number x . Ignore non-integer digits of x .
Make sure to truncate towards zero: a negative x must yield the closest greater integer (not lesser).
y = math.modf(x)
81
Declare the integer y and initialize it with the rounded value of the floating point number x .
Ties (when the fractional part of x is exactly .5) must be rounded up (to positive infinity).
function round(float)
    local int, part = math.modf(float)
    if float == math.abs(float) and part >= .5 then return int+1    -- positive float
    elseif part <= -.5 then return int-1                            -- negative float
    end
    return int
end
Alternative implementation:
function round(float)
    return math.floor(float + .5)
end
83
Declare regular expression r matching strings "http", "htttp", "httttp", etc.
r = "htt+p"
87
Exit immediately.
If some extra cleanup work is executed by the program runtime (not by the OS itself), describe it.
os.exit()
89
You've detected that the integer value of argument x passed to the current function is invalid. Write the idiomatic way to abort the function execution and signal the problem.
return nil, "Invalid argument x"
90
Expose a read-only integer x to the outside world while being writable inside a structure or a class Foo.
local Foo = {}
do
	local x = 0
	Foo.getX = function()
		return x
	end
end
print(Foo.getX()) -- 0
print(x) -- nil
Alternative implementation:
local function Foo()
    local private = {x = 9}
    local mt = {
        __index = private,
        __newindex = function (t, k, v)
            error("attempt to update a read-only table", 2)
        end
    }
    return setmetatable({}, mt)
end

local foo = Foo()
print(foo.x) -- 9
foo.x = 3    -- error: attempt to update a read-only table
91
Read from the file data.json and write its content into the object x.
Assume the JSON data is suitable for the type of x.
file = io.open("data.json")
x = cjson.decode(file:read("a"))
file:close()
92
Write the contents of the object x into the file data.json.
file = io.open("data.json", "w")
file:write(cjson.encode(x))
file:close()
93
Implement the procedure control which receives one parameter f, and runs f.
function control(f)
	f()
end
94
Print the name of the type of x. Explain if it is a static type or dynamic type.

This may not make sense in all languages.
print(type(x))
96
Set boolean b to true if string s starts with prefix prefix, false otherwise.
b = s:find(prefix, 1, true) == 1
Alternative implementation:
function startswith(text, prefix)
    return text:find(prefix, 1, true) == 1
end

b = startswith(s, prefix)
Alternative implementation:
b = string.sub(s, 1, #prefix) == prefix
97
Set boolean b to true if string s ends with string suffix, false otherwise.
b = s:sub(-string.len(suffix)) == suffix
99
Assign to the string x the value of the fields (year, month, day) of the date d, in format YYYY-MM-DD.
x = os.date("%F",d)
100
Sort elements of array-like collection items, using a comparator c.
table.sort(items,c)
105
Assign to the string s the name of the currently executing program (but not its full path).
s = arg[0]
106
Assign to string dir the path of the working directory.
(This is not necessarily the folder containing the executable itself)
dir = os.getenv("PWD") or io.popen("cd"):read()
107
Assign to string dir the path of the folder containing the currently running executable.
(This is not necessarily the working directory, though.)
dir = arg[1]
108
Print the value of variable x, but only if x has been declared in this program.
This makes sense in some languages, not all of them. (Null values are not the point, rather the very existence of the variable.)
if x then print(x) end
110
Set the boolean blank to true if the string s is empty, or null, or contains only whitespace ; false otherwise.
 blank = (s == nil or #string.gsub(s, "^%s*(.-)%s*$", "%1") == 0)
111
From current process, run program x with command-line parameters "a", "b".
os.execute(x .. 'a b')
112
Print each key k with its value x from an associative array mymap, in ascending order of k.
for k, x in pairs(mymap) do
  print(k, x)
end
116
Remove all occurrences of string w from string s1, and store the result in s2.
s2 = s1:gsub(w,"")
117
Set n to the number of elements of the list x.
local n = #x
118
Create the set y from the list x.
x may contain duplicates. y is unordered and has no repeated values.
local hash = {}
local y = {}
for _,v in ipairs(x) do
   if (not hash[v]) then
       y[#y+1] = v
       hash[v] = true
   end
end
119
Remove duplicates from the list x.
Explain if the original order is preserved.
local seen = {}
for index,item in ipairs(x) do
	if seen[item] then
		table.remove(x, index)
	else
		seen[item] = true
	end
end
120
Read an integer value from the standard input into the variable n
n = io.read("n")
122
Create an enumerated type Suit with 4 possible values SPADES, HEARTS, DIAMONDS, CLUBS.
Suit = {
    SPADES=1,
    HEARTS=2,
    DIAMONDS=3,
    CLUBS=4
}
123
Verify that predicate isConsistent returns true, otherwise report assertion violation.
Explain if the assertion is executed even in production environment or not.
assert(isConsistent() , "Assertion violation") 
126
Write a function foo that returns a string and a boolean value.
function foo()
	return "bar", false
end
131
Execute f1 if condition c1 is true, or else f2 if condition c2 is true, or else f3 if condition c3 is true.
Don't evaluate a condition when a previous condition was true.
if (c1) then f1()
elseif (c2) then f2()
elseif (c3) then f3()
end
133
Set boolean ok to true if string word is contained in string s as a substring, even if the case doesn't match, or to false otherwise.
ok = string.find( string.lower(s), string.lower(word) ) and true or false
134
Declare and initialize a new list items, containing 3 elements a, b, c.
items = {a, b, c}
137
Set the boolean b to true if the string s contains only characters in the range '0'..'9', false otherwise.
b = tonumber(s) ~= nil
138
Create a new temporary file on the filesystem.
file = io.tmpfile()
140
Delete from map m the entry having key k.

Explain what happens if k is not an existing key in m.
m[k]=nil
142
Assign to string s the hexadecimal representation (base 16) of integer x.

E.g. 999 -> "3e7"
s = string.format("%x",x)
144
Set boolean b to true if file at path fp exists on filesystem; false otherwise.

Beware that you should never do this and then in the next instruction assume the result is still valid, this is a race condition on any multitasking OS.
function exists(name)
    if type(name)~="string" then return false end
    return os.rename(name,name) and true or false
end
151
Remove last character from string p, if this character is the file path separator of current platform.

Note that this also transforms unix root path "/" into the empty string!
if string.sub(p, -1, -1) == "/" then
	p=string.sub(p, 1, -2)
end
152
Create string s containing only the character c.
s = c
153
Create the string t as the concatenation of the string s and the integer i.
t = s .. i
154
Find color c, the average between colors c1, c2.

c, c1, c2 are strings of hex color codes: 7 chars, beginning with a number sign # .
Assume linear computations, ignore gamma corrections.
local c = "#"
for i=2,#c1,2 do
	local avg = (tonumber(c1:sub(i,i+1), 16) + tonumber(c2:sub(i,i+1), 16)) / 2
	c = c .. string.format("%02x", math.floor(avg))
end
155
Delete from filesystem the file having path filepath.
os.remove(filepath)
157
Initialize a constant planet with string value "Earth".
PLANET = "Earth"
165
Assign to the variable x the last element of the list items.
local x = items[#items]
166
Create the list ab containing all the elements of the list a, followed by all the elements of the list b.
ab = {}

table.foreach(a, function(k, v) table.insert(ab, v) end)
table.foreach(b, function(k, v) table.insert(ab, v) end)
Alternative implementation:
ab = {}

table.move(a, 1, #a, 1, ab)
table.move(b, 1, #b, #ab + 1, ab)
167
Create string t consisting of string s with its prefix p removed (if s starts with p).
local t = (s:sub(0, #p) == p) and s:sub(#p+1) or s
168
Create string t consisting of string s with its suffix w removed (if s ends with w).
local t = s:gsub(w.."$", "")
169
Assign to the integer n the number of characters of the string s.
Make sure that multibyte characters are properly handled.
n can be different from the number of bytes of s.
local n = utf8.len(s)
170
Set n to the number of elements stored in mymap.

This is not always equal to the map capacity.
local n=0
for _ in pairs(mymap) do n=n+1 end
171
Append the element x to the list s.
s[#s + 1] = x
Alternative implementation:
table.insert(s, x)
182
Output the source of the program.
x = [["x = [" .. "[" .. x .. "]" .. "]\nprint(" .. x)]]
print("x = [" .. "[" .. x .. "]" .. "]\nprint(" .. x)
186
Exit a program cleanly indicating no error to OS
os.exit(0)
193
Declare two two-dimensional arrays a and b of dimension n*m and m*n, respectively. Assign to b the transpose of a (i.e. the value with index interchange).
local a = {}

for x = 1, n do
  local t = {}
  for y = 1, m do
    t[y] = {x, y}
  end
  a[x] = t
end
  
local b = {}

for y = 1, m do
  local t = {}
  for x = 1, n do
    t[x] = a[x][y]
  end
  b[y] = t
end
198
Abort program execution with error condition x (where x is an integer value)
os.exit(x)
200
Returns the hypotenuse h of the triangle where the sides adjacent to the square angle have lengths x and y.
local h = math.sqrt(x^2 + y^2)
204
Given a real number a, print the fractional part and the exponent of the internal representation of that number. For 3.14, this should print (approximately)

0.785 2
local function frexp(a)
	return math.frexp(a)
end
205
Read an environment variable with the name "FOO" and assign it to the string variable foo. If it does not exist or if the system does not support environment variables, assign a value of "none".
foo = os.getenv("FOO") or "none"
210
Assign, at runtime, the compiler version and the options the program was compilerd with to variables version and options, respectively, and print them. For interpreted languages, substitute the version of the interpreter.

Example output:

GCC version 10.0.0 20190914 (experimental)
-mtune=generic -march=x86-64
print(_VERSION)
219
Create the string t from the value of string s with each sequence of spaces replaced by a single space.

Explain if only the space characters will be replaced, or the other whitespaces as well: tabs, newlines.
local t = s:gsub("%s+", " ")
Alternative implementation:
local t
224
Insert the element x at the beginning of the list items.
table.insert(items, 1, x)
225
Declare an optional integer argument x to procedure f, printing out "Present" and its value if it is present, "Not present" otherwise
function f( x )
	if x then
		print("Present", x)
	else
		print("Not present")
	end
end
238
Write in a new byte array c the xor result of byte arrays a and b.

a and b have the same size.
local c = {}
for i=1,#a do
	c[i] = string.char(string.byte(a, i) ~ string.byte(b, i))
end
c = table.concat(c)
243
Print the contents of the list or array a on the standard output.
print(table.concat(a,", "))
256
Print the numbers 5, 4, ..., 0 (included), one line per number.
for i=5, 0, -1 do
	print(i)
end
272
Fizz buzz is a children's counting game, and a trivial programming task used to affirm that a programmer knows the basics of a language: loops, conditions and I/O.

The typical fizz buzz game is to count from 1 to 100, saying each number in turn. When the number is divisible by 3, instead say "Fizz". When the number is divisible by 5, instead say "Buzz". When the number is divisible by both 3 and 5, say "FizzBuzz"
n=1
while(n<=100) do
    out=""
    if(n%3==0) then
        out=out .. "Fizz"
    end
    if(n%5==0) then
        out=out .. "Buzz"
    end
    if(out=="") then
        out=out .. tostring(n)
    end
    print(out)
    n=n+1
end
276
Insert an element e into the set x.
x[e] = true
285
Given two floating point variables a and b, set a to a to a quiet NaN and b to a signalling NaN. Use standard features of the language only, without invoking undefined behavior.
local a = 0/0
289
Create the string s by concatenating the strings a and b.
local s = a..b
327
Assign to t the value of the string s, with all letters mapped to their lower case.
local t = string.lower(s)
328
Assign to t the value of the string s, with all letters mapped to their upper case.
local t = string.upper(s)