Jump to content




load function with table


6 replies to this topic

#1 EveryOS

  • Members
  • 570 posts
  • LocationOver there ->

Posted 29 May 2018 - 11:57 PM

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?

#2 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 30 May 2018 - 01:35 AM

What are the second return values when it returns nil for the first return value?

#3 valithor

  • Members
  • 1,053 posts

Posted 30 May 2018 - 01: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 by valithor, 30 May 2018 - 01:49 AM.


#4 Bomb Bloke

    Hobbyist Coder

  • Moderators
  • 7,099 posts
  • LocationTasmania (AU)

Posted 30 May 2018 - 01: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 {}")


#5 EveryOS

  • Members
  • 570 posts
  • LocationOver there ->

Posted 30 May 2018 - 12:13 PM

Ok, I'll try that

#6 EveryOS

  • Members
  • 570 posts
  • LocationOver there ->

Posted 30 May 2018 - 12:32 PM

View PostBomb Bloke, on 30 May 2018 - 01:53 AM, said:

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.

#7 Sewbacca

  • Members
  • 450 posts
  • LocationStar Wars

Posted 28 June 2018 - 03:40 PM

View PostEveryOS, on 30 May 2018 - 12:32 PM, said:

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 by Sewbacca, 28 June 2018 - 03:42 PM.






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users