Dumb example to demonstrate literate programming.
This quick example demonstrates how to write a Lua program that outputs the first 100 prime numbers. Let's start by defining a configurable variable that tells us how many primes to output.
local NUMBER_OF_PRIMES = 100 -- Change this to output more or less primes.
Now we'll create a helper function that can actually check if a number is prime.
function isPrime(num)
if num < 2 then return false end
if num == 2 then return true end
for i=2,num - 1 do
if num % i == 0 then return false end
end
return true
end
Finally, we can print out the prime numbers. We create two counters - one holding the number that we are checking (number
) and one holding the number of primes that we have found so far (counter
). We know that the first prime number is 2
, so we start with number = 2
.
local count, number = 0, 2
while count < NUMBER_OF_PRIMES do
if isPrime(number) then
print(number)
count = count + 1
end
number = number + 1
end