Answers to exercises from Day 1 of learning Lua from "7 More languages in 7 weeks"
function ends_in_3(num)
return string.sub(string.reverse(num), 1, 1) == "3"
end
print("Checking ends_in_3...")
print(ends_in_3(3))
print(ends_in_3(2))
print(ends_in_3(0))
function is_prime(num)
for i = 2, (num - 1) do
if ((num % i == 0) and (i ~= num)) then
return false
end
end
return true
end
print("Checking primes...")
print(is_prime(0) == true)
print(is_prime(1) == true)
print(is_prime(2) == true)
print(is_prime(3) == true)
print(is_prime(4) == false)
print(is_prime(5) == true)
print(is_prime(13) == true)
print(is_prime(14) == false)
function first_n_primes_ending_in_3(n)
local number_found = 0
local current_number = 0
while (number_found < n) do
current_number = current_number + 1
if (is_prime(current_number) and ends_in_3(current_number)) then
print(current_number)
number_found = number_found + 1
end
end
end
print("Printing first_n_primes_ending_in_3...")
-- first_n_primes_ending_in_3(1)
first_n_primes_ending_in_3(10)
function for_loop(a, b, f)
local i = a
while (i <= b) do
f(i)
i = i + 1
end
end
function printer(num)
print(num)
end
print("Hacking for loop...")
for_loop(1, 5, printer)
function reduce(max, init, f)
if (max == 0) then
return init
end
return reduce(max - 1, f(init, max), f)
end
function add(previous, next)
return previous + next
end
print("Reducing addition...")
print(reduce(5, 0, add))
function multiply(a, b)
return a * b
end
function factorial(num)
return reduce(num, 1, multiply)
end
print("Factorial...")
print(factorial(8))