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.
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.
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.
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.
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" ()
Lua 5.1.3require
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With