SudoGaron
SudoGaron

Reputation: 438

How do I load data from another lua file?

I have a main lua file app.lua , and in that app I have a button to "load data" in. NOTE: LUA 5.1 not 5.2

The data file is a lua file as well with tables in it.

data1 = {
  {a,b,c},
  {1,2,3}
}
data2 = {
  {d,e,f}
}

The goal was to make those tables available to the app anytime I choose to load the file.

I tried the example from the lua site

    function dofile (filename)
      local f = assert(loadfile(filename))
      return f()
    end

but f() is just printing a massive string. I can't seem to access f.data1[1] for example.

Upvotes: 1

Views: 2290

Answers (1)

Vlad
Vlad

Reputation: 5867

The file you're loading is not a data table. That's a piece of code, anonymous function that is executable. You run that code in return f() statement.

But see what that code does - it doesn't return anything. Instead it assigns two global variables, data1 and data2. You can access those as data1[1] for example.

You could return the data in the file being loaded, that way it wouldn't pollute the global environment, and probably will look like you imagined it to be:

return {
  data1 = { {a,b,c}, {1,2,3} },
  data2 = { d,e,f}
}

And in other file:

local f = assert(loadfile(filename))
my_data = f()
print(my_data.data1[1][1])

Upvotes: 3

Related Questions