Back to code Lua

Recordar resultados caros para no calcularlos dos veces

Memoización en diez líneas: una función que envuelve a otra y guarda lo que ya respondió.

This post is not in your language yet; you are seeing it in Spanish. The code is the same.

The problem

Una función se llama cientos de veces con los mismos argumentos y cada llamada cuesta: una consulta, un cálculo pesado. Calcular una vez y recordar es la optimización más barata.

Lua
local function memoizar(fn)
  local cache = {}
  return function(n)
    local v = cache[n]
    if v == nil then
      v = fn(n)
      cache[n] = v
    end
    return v
  end
end

local precio_con_impuesto
precio_con_impuesto = memoizar(function(codigo)
  print("  (calculando " .. codigo .. ")")      -- simula una consulta cara
  local base = ({ A1 = 100, B2 = 250 })[codigo] or 0
  return base * 1.07
end)

print(precio_con_impuesto("A1"))   -- calcula
print(precio_con_impuesto("A1"))   -- sale de la caché
print(precio_con_impuesto("B2"))   -- calcula

Why it is written this way

  1. memoizar recibe una función y devuelve otra que hace lo mismo, pero consulta primero su tabla.
  2. La tabla cache vive en el cierre: cada función memoizada tiene la suya y nadie más la ve.
  3. En Lua las tablas son a la vez diccionario y arreglo, así que la caché no necesita ninguna estructura especial.
  4. El mensaje "calculando" aparece dos veces en tres llamadas: esa es la prueba de que funciona.
How to try it

Guardalo como memo.lua y corré: lua memo.lua

Watch out

La caché no vence nunca: si el precio cambia, la función sigue devolviendo el viejo. Y un resultado nil no se guarda, así que se recalcula cada vez.

Adapt it to your case with AI

The button copies this prompt with the code pasted below it. Replace the brackets with your own details and paste it into ChatGPT, Claude, Gemini or Copilot.

The prompt
Tengo esta memoización en Lua. Extendela para funciones de varios argumentos, con vencimiento de [SEGUNDOS] segundos por entrada y un tope de [CANTIDAD] entradas descartando la más vieja. La voy a usar en [DÓNDE: un juego con LÖVE, Nginx con OpenResty, Redis, Neovim]. Agregá una función para vaciar la caché a mano y mostrame cómo medir cuántos aciertos tiene.

Example written and reviewed by hand.

Share

Comments

No comments yet. Yours can be the first.

Plain text only, no links. No email is requested. Comments are reviewed before they are published.

Did you adapt it to something of yours?

Tell me what you solved with it, or what it was missing.

Keep trying

More code

See all
Darinel Ortega Online · I reply during the day
Today
Hello. I'm not selling anything here: this is for exchanging knowledge about technology.
Write whatever you like — you can send text, images or documents. Messages reach my console and I reply from there.
You are writing outside working hours. I will read you as soon as the day starts.

An open conversation to share knowledge. Messages reach my console and I reply from there.

Let us book a conversation

Pick the day and time that work for you. Thirty minutes, no sales pitch.

Video call

For a video call, just ask for one here and I'll send you the session link.