string.dump()
The string.dump()
function generates a binary string representing a precompiled version of a Lua function. This is useful for serializing or transmitting Lua functions, as well as for debugging purposes.
Syntax
string.dump(function, stripDebug)
Parameters
- Name
function
- Type
- function
- Description
The Lua function to be dumped into a binary representation.
- Name
stripDebug
- Type
- boolean
- Description
If set to
true
, debug information (like line numbers) will be stripped from the dumped string, resulting in a smaller binary size.
Return Value
The function returns:
- A binary string containing the precompiled representation of the Lua function.
Examples
Example 1: Dump a simple function
The function is dumped into its binary representation.
Example 1
local function greet()
return "Hello, world!"
end
local dumped = string.dump(greet)
print(dumped)
-- Output: A binary string representing the compiled function
Example 2: Serialize and reuse a function
Dump a function, save it to a file, and load it later.
Example 2
local function square(x)
return x * x
end
-- Serialize the function to a file
local dumped = string.dump(square)
local file = io.open("square_function.bin", "wb")
file:write(dumped)
file:close()
-- Later, load the function back
local file = io.open("square_function.bin", "rb")
local binary = file:read("*a")
file:close()
local loadedFunction = load(binary)
print(loadedFunction(5)) -- Output: 25
Example 3: Strip debug information
Use the stripDebug
parameter to create a more compact binary representation.
Example 3
local function sum(a, b)
return a + b
end
local dumped = string.dump(sum, true) -- Strips debug information
print(dumped)
-- Output: A smaller binary string
Example 4: Error handling
string.dump()
only works with Lua functions. Attempting to dump a non-function value will raise an error.
Example 4
-- print(string.dump("not a function"))
-- Error: bad argument #1 to 'dump' (function expected, got string)
Use Cases
- Serialization: Save functions for reuse or transmission.
- Debugging: Analyze or compare the internal representation of Lua functions.
- Optimization: Strip debug information to reduce binary size for production use.
See also
load()
: Reconstructs a function from a binary string generated bystring.dump()
.loadstring()
: Similar toload()
, but used for loading Lua code from strings (deprecated in Lua 5.2+).io.open()
: Useful for saving or loading dumped functions from files.