lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 05/05/2017 07:14 AM, Jorge Eduardo de Araújo Oliveira wrote:
> Hi, guys!
> 
> I know it sounds noob, but it's noob !! LOL!
> I'm studing Lua Programming for a few weeks...
> 
> The question is:
> How do I store user input in a table/array?
> 
> For example, information from a school report card:
> 
> Name Grade_1 Grade_2 Average_Grade
> 
> John    7.0        8.0             7.5
> 
> I'm worried about this.
> Thanks a lot for the help!
> 

Hi,

as Andrew Starks pointed, first you mush decide how data structure
should look like. Probably you need just a sequence of records, where
each record is set of string fields "name", "grade_1", "grade_2",
"avg_grade".

Then you just create table for storing them:

  local data = {}

And populate it with records:

  local record = {}
  record.name = get_name()
  record.grade_1 = get_grade_1()
  ...
  data[#data + 1] = record

Alternatively, you may create each record at once:

  local record = {
    name = get_name(),
    grade_1 = get_grade_1(),
    grade_2 = get_grade_2(),
    avg_grade = get_avg_grade(),
  }
  data[#data + 1] = record

Then you may iterate <data> to get (or modify or even add/remove) it's data:

  for i = 1, #data do
    local rec = data[i]
    print(('[%d] name: %s, grade_1: %s, grade_2: %s, avg_grade:
%s'):format(i, rec.name, rec.grade_1, rec_grade_2, rec.avg_grade))
  end

Tables (along with functions) is crucial Lua language part. It's power
mostly relies on them. I recommend to read about them in Reference
Manual to understand all possible usages.

-- Martin