Blog Index

Sam Trenholme’s blog

Some Lua stuff

October 9, 2025

I post some code to find the greatest common divisor (GCD) of two numbers.

The code to find a GCD

To use this code, one must have the function primes() which I posted on September 17th, as well as the function factor() which I posted on September 18th.

function GCD(a,b)
  local fa = factor(a)
  local fb = factor(b)
  local out = 1
  b = 1
  for a=1,#fa do
    if fb[b] and 
       fa[a] == fb[b] then
      out = out * fa[a]
      b = b + 1
    end
    while fb[b] and 
          fb[b] < fa[a] do
      b = b + 1
    end
  end
  return out
end

This code is useful when reducing fractions, something I will post in a future blog.

Force globals to be declared in Lua

One complaint people have about Lua is that the default scope of variables is global. This can cause typos to be hard to debug, e.g.

function foo(a)
  local the = "The the"
  local out = tostring(teh) 
        .. " " .. a
  return out
end

Here, it might be difficult to determine why “the” is not affecting the output of the function, because “teh” here is a typo. Since “teh” is undeclared, it defaults to having the value nil which can cause, in code examples more complicated than this, code to act in unusual ways which are hard to debug.

However, it’s been possible, since Lua 5.1 (actually 5.0, but 5.1 is a very widely used version of Lua), to force globals to be declared in Lua scripts. This is discussed in the Programming in Lua book, but the code here has been rewritten to be public domain instead of under an unknown copyright.

_PROMPT="] " -- For the CLI
_PROMPT2="]] " -- For CLI
function set(name, val)
  rawset(_G, name, 
         val or false)
end
function exists(name)
  if rawget(_G, name) then
    return true 
  end
  return false
end
throwError = 
{__newindex = 
  function(self,name)
    error("Unknown global "
          .. name) 
  end
  ,
 __index = 
  function(self,name)
    error("Unknown global "
          .. name) 
  end
}
setmetatable(_G,throwError)

To use:

set("a") 
a = 1

Or like this:

repeat
local a
a = 1
until true

Go to: Older - Newer - All entries - Index