lua-users home
lua-l archive

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


On Fri, May 5, 2017 at 9:14 AM, Jorge Eduardo de Araújo Oliveira
<jorgeeduardoaoliveira@gmail.com> 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!
>

Tables are supremely flexible, able to store any and all value types
in the key or the value (except that nil cannot be a key).

So, in your example, we can take any one of multiple approaches,
depending upon what it is you want to accomplish! For example:

```
data = {John = {Grade_1 = 7.0, Grade_2 = 8.0, Average_Grade = 7.5}}
```

Here, the value of `data.John` is a table with three fields: Grade_1,
Grade_2 and Average_Grade

But what if there's more than one John? This won't work if you have
two Johns. Instead of indexing on the name, you might choose some
unique identifier, like their student ID number. But failing that, you
can change the model so that you store all students in an array.

data = {
  {Name = "John", Grade_1 = 7.0, Grade_2 = 8.0, Average_Grade = 7.5}
}

Now data can behaves like an array, complete with a length operator.
This table has one array element at index 1.

```
print(#data) --the length of data, aka the number of records.
--> 1
print(data[1].Name) --the value of the `Name` field of the first element.
--> John
```

There are about 500 other ways that you can store this data. Also, you
can add behaviors, such as having the Average_Grade field calculate
itself.

Hope this helps!

-Andrew





-- 
Andrew Starks
612 840 2939
andrew@starksfam.org