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 = ?
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.
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