🎓 A1Learner
🔍
0 of 49 lessons completed

Lua LuaJIT Notes

LuaJIT notes describe what changes when code runs under LuaJIT. LuaJIT is a just-in-time compiler for Lua.

A tight loop is the shape a JIT favours

LuaJIT note: this is the kind of loop a just-in-time compiler translates while it runs. The block itself is ordinary plain Lua, and it only shows the loop result.

local total = 0
for i = 1, 100 do total = total + i end
print(total)

Plain numbers and locals suit a JIT loop

LuaJIT note: simple numeric work with locals is easy for a compiler to follow. The block itself is ordinary plain Lua, and it only shows the total.

local total = 0
local step = 2
for i = 1, 5 do total = total + step end
print(total)

FFI is a LuaJIT-only bridge

LuaJIT note: FFI lets Lua code call code written in another language. Plain Lua has no FFI, so this block only shows an ordinary Lua function call.

local function outside(x) return x * 2 end
print(outside(21))

Example

local total = 0
for i = 1, 10 do
  local square = i * i
  total = total + square
end
print(total)

Key points

  • Just-in-time compiler: a compiler that translates code while the program runs.
  • Hot code: code that runs many times, such as a tight numeric loop.
  • Tight loop: a short loop that repeats simple numeric work.
  • Under LuaJIT, a tight numeric loop may run faster because the compiler translates it while it runs.
  • FFI: a foreign function interface, a way for Lua code to call code written in another language.

In this example, a loop squares each number with a local and adds it to the total. LuaJIT note: this ordinary plain Lua loop is the shape a just-in-time compiler handles well, but no LuaJIT result is claimed here.

Note

FFI code is specific to LuaJIT, so it does not run on plain Lua.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does FFI let Lua code do under LuaJIT?