Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return multiple modules in Lua?

Tags:

module

lua

How can I return multiple tables/objects in Lua? I have this in file1.lua:

local A = {}
function A.new()
    o = {}
    return o
end
local B = {}
function B.new()
    o = {}
    return o
end

return A        --And I want to return B

And I want to use them both in file2.lua:

local A = require "file1"
a = A.new()
b = ?

1 Answers

You probably can return few results like this:

return A, B
…
local A,B = require "file1"

But this is a bad idea because of caching and will likely fail.

Better put them both into table:

return {A = A, B = B}
…
local file1 = require "file1"
local A,B = file1.A, file1.B

UPD: This will work only in lua 5.2+, but probably is shortest and clearest one:

return {A, B}
…
local A, B = table.unpack(require "file1")

You can use any on last two.

like image 57
val is still with Monica Avatar answered Oct 22 '25 16:10

val is still with Monica