문제

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