This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
EveryOS's profile picture

load function with table

Started by EveryOS, 29 May 2018 - 10:57 PM
EveryOS #1
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?
Lyqyd #2
Posted 30 May 2018 - 02:35 AM
What are the second return values when it returns nil for the first return value?
valithor #3
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
Bomb Bloke #4
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 {}")
EveryOS #5
Posted 30 May 2018 - 01:13 PM
Ok, I'll try that
EveryOS #6
Posted 30 May 2018 - 01:32 PM
load("return {}")
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.
Sewbacca #7
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