4

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 = ?
float
  • 371
  • 1
  • 6
  • 16
  • 2
    Your code defines A and B as globals, and so they are accessible in file2.lua. – lhf Apr 03 '19 at 20:39
  • My original answer was, indeed, incorrect. The next best solution is probably: https://stackoverflow.com/questions/9470498/can-luas-require-function-return-multiple-results – brianolive Apr 04 '19 at 11:09

1 Answers1

3

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.

val - disappointed in SE
  • 1,475
  • 3
  • 16
  • 40