🎓 A1Learner
🔍
0 of 49 lessons completed

Lua Code Generation

Code generation builds a code string from data and turns it into a function. The built function then runs like any other function.

A value from data becomes part of the code

The number 5 is joined into a code string. Loading the string gives an adder function.

local n = 5
local code = "return function(x) return x + " .. n .. " end"
local f = load(code)
local add = f()
print(add(10))

A generated function uses its passed environment

The code reads base from the passed table. No other outside value is needed.

local env = {base = 100}
local f = load("return base + 23", nil, "t", env)
print(f())

A template can build a function that returns text

string.format puts a quoted word into the code. The generated function returns that word.

local code = string.format("return function() return %q end", "Ada")
local f = load(code)
local greet = f()
print(greet())

Example

local factors = {2, 3, 4}
local funcs = {}
for i, factor in ipairs(factors) do
  local code = string.format("return function(x) return x * %d end", factor)
  local f = load(code)
  funcs[i] = f()
end
print(funcs[1](10))
print(funcs[2](10))
print(funcs[3](10))

Key points

  • Template: a template is a code string with a value filled in from data.
  • string.format: string.format fills values into a code string in place of markers.
  • load: load turns the built code string into a function.
  • Environment: a generated function runs under the environment table passed to load.
  • Reuse: build a generated function once, then call it many times.

In this example, each factor is formatted into its own code string. Each string is loaded into a multiplier function. Calling the three functions with 10 prints 20, 30, and 40.

Note

never build code from untrusted text, because loaded code runs with the powers of its environment table.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

You build the string "return function(x) return x * 4 end" and load it. What do you get back?