749 posts
Location
BOO!!
Posted 30 May 2018 - 12:57 AM
I tried these three snippets of code on 1.74:
load(function() end)--returns a function
load(function() return {} end) --returns nil
local e = {}
load(function() e.h = "h"; return e end) --returns nil
How come the last two invokes return nil, and is there away around this?
8543 posts
Posted 30 May 2018 - 02:35 AM
What are the second return values when it returns nil for the first return value?
1023 posts
Posted 30 May 2018 - 02:49 AM
https://www.lua.org/...l.html#pdf-load load (ld [, source [, mode [, env]]])
"If ld is a string, the chunk is this string. If ld is a function, load calls it repeatedly to get the chunk pieces. Each call to ld must return a string that concatenates with previous results. A return of an empty string, nil, or no value signals the end of the chunk."
The argument to load must either be a string or a function that returns a string.
Edited on 30 May 2018 - 12:49 AM
7083 posts
Location
Tasmania (AU)
Posted 30 May 2018 - 02:53 AM
Note that while Lua 5.1 (used by ComputerCraft) usually only accepts string-returning functions, Dan's added some 5.2 support in through bios.lua, meaning you can pass strings to load() directly (per the documentation valithor linked).
So:
load("return {}")
749 posts
Location
BOO!!
Posted 30 May 2018 - 01:13 PM
Ok, I'll try that
749 posts
Location
BOO!!
Posted 30 May 2018 - 01:32 PM
Ok, that works, thanks, but I found something that works even better:
load(string.dump(someFunction))
Your comment made me think of it though, since you pointed out that load can load strings just fine.
463 posts
Location
Star Wars
Posted 28 June 2018 - 04:40 PM
Your comment made me think of it though, since you pointed out that load can load strings just fine.
Please use it in just this case: You want to change the environment of a function and you don't know the origin of that one.
Because the debug information would get lost, so you won't know in which line an error occur.
Note, string.dump removes all connections to the old environment.
local n = 0
function foo()
n = n + 1
return n
end
If you would use this:
load(string.dump(someFunction))
It would throw something like this:
string:-1: attempt to add on nil and number
Please use string.dump only in the case you want to save a anonymous (!) function to a file.
Edited on 28 June 2018 - 02:42 PM