how do I collect the function return in load

Viewed 321

I'm now starting to study the load() function in lua, and I'm having trouble getting the value that the function returns

I tried these two ways to execute a function with load() and collect their value

function sumvalues()
    return 5+3
end

local func = "sumvalues()"

print(load(func))

local func = "return 5+3"

print(load(func))

but they only return the function, not the value returned from them

function: 0000000000cf0e50
function: 0000000000cf0df0

does anyone know how I can perform a function with load() and collect their return?

I also wanted to know how I do to collect a variable using a string with the same name as the variable in load(), I tried to do this:

hello = "Hello World"

print(load("hello"))

but he gives this error:

nil [string "hello"]:1: syntax error near <eof>

would anyone know how i can do this wonder? thanks for your attention !

1 Answers

When you pass a string to load, the chunk is compiled (in the global environment) and a function is returned that executes that chunk. In order to execute that chunk, you have to call the function:

> function sumvalues()
>> return 5+3
>> end
> func = "return sumvalues()"
> load(func)
function: 0x55e069c2a490
> load(func)()
8

Here func is a string that is taken as a chunk and compiled by load as the body of a function which returns the value returned from calling sumvalues. Note that since load compiles its chunks in the global environment, local func = "return sumvalues()" will not work, because then func would not be visible to load.

Another example:

> hello = "return 'Hello World'"
> load(hello)()
Hello World
> print(load(hello))
function: 0x55e069c53580
> print(load(hello)())
Hello World

Here, the chunk "return 'Hello World'" is compiled to a function that returns the string 'Hello World'. You can call that function, print the value of that function, or print the value returned by calling that function.

If it seems like too much work to have to prepend "return " on the front of the code string, you could make a function like chunkify:

function chunkify (s)
  return "return " .. s
end

> load(chunkify("5+3"))()
8
> load(chunkify("'Hello World'"))()
Hello World

You are still passing a string containing the code that you want to run, so any strings within that code need to be quoted, too.

> load(chunkify("function (x) return 2*x end"))()(21)
42

The function returned by load does not take any arguments, but you can create such a function using load by compiling a chunk that itself returns a function that does take arguments. The function returned by load will have to be called in order to access the real function of interest. Above, see that the function returned by load is called with the first (), and the following (21) calls the function returned by the chunk.

Related