1

I want to read a table inside a Lua file before executing it. Is there a way to do this with loadfile. It returns only a function and I can't seem to be able to read what is inside (what is declared but not executed).

The other option I tried is to check if the environment changed, but yet again I couldn't read inside the function returned by loadfile().

Is there a way to do this without opening the file as text and searching the table?

Here is an example of the table I try to retrieve:

--file to be loaded  
local library = require("library")  --random requires...  
table = { author = "myself", dependencies = "library > 1.0"} --table to get before execution
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Gopoi
  • 113
  • 7

1 Answers1

1

What you want is not possible. There are no declarations in Lua, only executable statements. You need to execute a script to see what it does.

However, you could read the file as text and try to extract the info you need using pattern matching. This won't be foolproof but it'll probably work in most cases if the files are written in the same way.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • It is suposed to be a standard header in a file. Would it be weird to obligate the user to create a main function and I would call it? – Gopoi Apr 27 '15 at 16:36
  • @Gopoi, a common pattern is for a script to return prescribed values, such as one value that is a table, because, as you've found, `loadfile` does create a function from the file. This formalized in Lua 5.2's `require` function. See this [Basic Example](https://john.nachtimwald.com/2014/07/19/writing-lua-modules/). – Tom Blodget Apr 28 '15 at 00:08