I'm working on a Lua project for college, but this is the first time I'm seeing Lua, so I don't know everything my teachers asked me to do.

I need to read a file, we must say "text.txt", which its data are organized this way:

entry
{
--
name = "John",
--
sex = "M" ou "F",
--
age = 20,
--
}

Then I need to put this data in an array so I can use them later.

Does anyone know how to do it and can help me with this code?

有帮助吗?

解决方案

This format is a subset of Lua syntax, so you should have a fairly easy time of parsing it, assuming you're allowed to use some library functions.

As far as the format of the file goes: f{ ...} is syntactic sugar for f({...} as a function call. The rest of the stuff in the braces is comments (starting with --) and table fields (age = 20,)

So, for instance, the example above (with "M" where we had a choice) would parse as the function call entry({name = "John", sex = "M", age = 20}) which is valid Lua code, and can be parsed with the functions load(string) or loadfile(path in the standard library.


To actually extract the data, you'll need to do something along these lines:

local filecontents = [the contents of your file as a string]
local entries = {}
do
  -- define a function that our data-as-code will call with its table
  -- its job will be to simply add the table it gets to our array. 
  local function entry(entrydata)
    table.insert(entries, entrydata)
  end

  -- load our data as Lua code
  local thunk = load(filecontents, nil, nil, {entry = entry})
  thunk()


end
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top