Programming by lua 11.2

I have been reading programmming by lua (first edition) book and I came across I thing which I can’t understand.
The link to the chapter in online version is here: Programming in Lua : 11.2

Can somebody explain to me what this book is trying to do here?

"The second way to represent a matrix in Lua is by composing the two indices into a single one. If the two indices are integers, you can multiply the first one by a constant and then add the second index. With this approach, the following code would create our matrix of zeros with dimensions N by M :

  mt = {}          -- create the matrix
    for i=1,N do
      for j=1,M do
        mt[i*M + j] = 0

If the indices are strings, you can create a single index concatenating both indices with a character in between to separate them. For instance, you can index a matrix m with string indices s and t with the code m[s..':'..t] , provided that both s and t do not contain colons (otherwise, pairs like ( "a:" , "b" ) and ( "a" , ":b" ) would collapse into a single index "a::b" ). When in doubt, you can use a control character like \0` ´ to separate the indices."

In loosely-typed languages like Lua, a lot of people throw around a lot of terms and vocabulary that isn’t official and is more slang. This is sort of what is happening here.

What it’s saying is that you have two options when composing a standard “matrix” in Lua. A matrix is a set of data that has identifiers with a row and a column. Such as

[ 0 0 0 ]
[ 1 2 3 ]
[ 3 4 5 ]

Number 2 is at row 2 and column 2.

This tutorial is saying that you can create something like this by putting tables within other tables (the first explanation).

	{ 0; 0; 0; };
	{ 1; 2; 3; };

Which you can then access like this

local row2Column2 = tab[2][2]

However, it also goes into a second explanation which says you can do this without tables inside tables and just have something like this.

{0; 0; 0; 1; 2; 3; 5; 6; 4;}

Where the indices (the way you access the table with []) would be the row multiplied by the column size plus the column’s index in the row. So row 2 column 2 would be index 8 (2 x 3 + 2 = 8).

It’s honestly a weirdly silly way for them to try explaining multi-dimensional tables.


But the 8th index of the table has a value of 6 not 2. The book says add 2 but to get the value of row two and column two, should we minus 2?

Just use (row -1)

No, it doesn’t. In my example above it does visually, but in the Lua tutorial you linked they set the indices to custom numerical values in a for loop.

Can you also explain the string thing too pls?