Lua Cheatsheet

Coroutines, Embedding, and Performance

Use this Lua reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Coroutine Basics

local co = coroutine.create(function()
  coroutine.yield('first')
  return 'done'
end)

print(coroutine.resume(co)) -- true first
print(coroutine.resume(co)) -- true done

Coroutines are cooperative. They run until they yield, return, or error. They do not preempt each other like OS threads.

Coroutine Iterator

local function range(n)
  return coroutine.wrap(function()
    for i = 1, n do
      coroutine.yield(i)
    end
  end)
end

for n in range(3) do print(n) end

coroutine.wrap returns a function that resumes the coroutine each time it is called.

Scheduling Pattern

local tasks = {}

local function spawn(fn)
  tasks[#tasks + 1] = coroutine.create(fn)
end

local function tick()
  for i = #tasks, 1, -1 do
    if coroutine.status(tasks[i]) == 'dead' then
      table.remove(tasks, i)
    else
      assert(coroutine.resume(tasks[i]))
    end
  end
end

Game engines and embedded runtimes often build small cooperative schedulers on top of coroutines.

Embedding Mindset

Lua is frequently embedded in C/C++, games, Redis scripts, Neovim config, and application plugins. Embedded Lua usually means the host controls available libraries, IO, sandboxing, and lifecycle.

Sandbox Checklist

  • Do not expose os.execute, unrestricted file IO, or debug APIs to untrusted scripts.
  • Provide a narrow API table instead of the full global environment.
  • Set instruction or time limits in the host when possible.
  • Validate script outputs before using them in the host app.

Performance Habits

local insert = table.insert
local out = {}
for i = 1, n do
  insert(out, tostring(i))
end
local text = table.concat(out, ',')

Cache hot global lookups in locals when profiling proves it matters. Use table.concat for repeated string building.

Avoid Accidental Holes

local t = {1, 2, nil, 4}
print(#t) -- not a reliable count for a sequence with holes

The length operator is defined for sequences without holes. Track counts explicitly when nil can appear.

LuaJIT Note

LuaJIT has different performance behavior and FFI features from standard Lua. Check the target runtime before relying on LuaJIT-only APIs or optimization folklore.