string.dump
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.
|
|||
This dumps a function, writes the dump to a file, and then loads it again. | |||
Code | <nowiki>
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)()
</nowiki>
|
||
Output | Prints 0 1 2 3 4 5 6 7 8 9 10 which is the output of the original function. |
|
|||
Upvalues are not preserved when a function is dumped and loaded, which can cause problems | |||
Code | <nowiki>
-- 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()
</nowiki>
|
||
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 . |
|
|||
os.queueEvent is defined in CC itself, and has no Lua source code. | |||
Code | <nowiki>
string.dump(os.queueEvent)
</nowiki>
|
||
Output | Produces the error Unable to dump given function . |
string.dump Function | |
---|---|
Syntax string.dump(
| |
Returns | string |
API | string |
Source | Lua (source) |
This article is issued from Computercraft. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.