Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Lua's require function return multiple results?

Tags:

It is possible to create a Lua module which returns multiple results via the require function? I'm currently writing an extension to package.loaders and I want to know if I need to support such behavior.

For example, take the following module, named mod.lua:

print("module loading")
return "string1", "string2"

Which is required by the following script:

print("running script")
s1, s2 = require("mod")
print("s1: " .. tostring(s1))
print("s2: " .. tostring(s2))

Results in the following output:

running script
module loading
s1: string1
s2: nil

When I would expect the second string to be returned. I'm not looking to use such behavior, and I realise that you could replicate it by returning a table and unpacking that, I just want to know if it's meant to work (as it's valid Lua syntax) and I can't find a definitive answer on this anywhere.

like image 506
GooseSerbus Avatar asked Feb 27 '12 18:02

GooseSerbus


People also ask

Can you have a function return multiple values?

JavaScript functions can return a single value. To return multiple values from a function, you can pack the return values as elements of an array or as properties of an object.

How do you return a value from a function in Lua?

Function return values In most languages, functions always return one value. To use this, put comma-separated values after the return keyword: > f = function () >> return "x", "y", "z" -- return 3 values >> end > a, b, c, d = f() -- assign the 3 values to 4 variables.

How does Lua require work?

Lua offers a higher-level function to load and run libraries, called require . Roughly, require does the same job as dofile , but with two important differences. First, require searches for the file in a path; second, require controls whether a file has already been run to avoid duplicating the work.


2 Answers

You could always return a function from your module and have that return multiple values, like below:

foo.lua

return function() return "abc", 123 end

bar.lua

local a, b = require "foo" ()
like image 91
Peter Smith Avatar answered Sep 20 '22 20:09

Peter Smith


Lua 5.1.3
require lua export implemented in static int ll_require (lua_State *L) in loadlib.c file. This functions always returns 1 as number of returned values on stack.

like image 36
Andrey Starodubtsev Avatar answered Sep 23 '22 20:09

Andrey Starodubtsev