string.dump

From ComputerCraft
Jump to navigation Jump to search

string.dump
Function
Syntax
string.dump()
Returns string
API string
Source Lua (source)

Converts a function to a binary representation which can later be converted back to a function using loadstring. Functions not defined in Lua code (i.e. native CC functions such as type, pcall and os.date) cannot be dumped. Upvalues (local variables defined outside of a function and used within it) are not preserved.

Error creating thumbnail: Unable to save thumbnail to destination
ExampleDump and load a function
This dumps a function, writes the dump to a file, and then loads it again.
Code
local function example1()
    for i = 0, 10 do write(i .. " ") end
end

local f = fs.open("test", "w")
f.write(string.dump(example1))
f.close()

local f = fs.open("test", "r")
local dump = f.readAll()
f.close()

loadstring(dump)()
Output Prints 0 1 2 3 4 5 6 7 8 9 10 which is the output of the original function.
Error creating thumbnail: Unable to save thumbnail to destination
ExampleDump a function with upvalues
Upvalues are not preserved when a function is dumped and loaded, which can cause problems
Code
-- Within the example2 function, this is an upvalue
local x = "world"

local function example2()
    print("Hello", x)
end

print "example2 called directly"
example2()

print "example2 dumped and loaded, then called"
local dump = string.dump(example2)
local fn = loadstring(dump)
fn()
Output Prints Hello world when example2 is called directly, but prints Hello nil after the dump of example2 is loaded. x is "world" within example2, but within the dumped and loaded version it is nil.
Error creating thumbnail: Unable to save thumbnail to destination
ExampleDump a function not defined in Lua.
os.queueEvent is defined in CC itself, and has no Lua source code.
Code
string.dump(os.queueEvent)
Output Produces the error Unable to dump given function.