aquagremlin
aquagremlin

Reputation: 3549

How to display 2D array in Lua

This works:

mt = {}          -- create the matrix
    for i=1,5 do
     mt[i] = {}     -- create a new row
      for j=1,3 do
        mt[i][j] = j
        print(i,j)
      end
    end

but this does not

mt = {}          -- create the matrix
    for i=1,5 do
     mt[i] = {}     -- create a new row
      for j=1,3 do
        mt[i][j] = j
        print(i,j)
        print mt([i][j])
      end
    end

and gives the error

'=' expected near 'mt'

using this statement

print(i,j,mt([i][j]))

gives this error

unexpected symbol near '['

I did read this thread How do I display array elements in Lua?

but my question is more fundamental about the proper syntax.

Upvotes: 1

Views: 3210

Answers (1)

Patronics
Patronics

Reputation: 1389

The problem is the opening parenthesis should be immediatly following Print not after the mt, You need to move the parenthesis, resulting in the code for that line:

print(mt[i][j])

Making the complete code snippet be:

mt = {}          -- create the matrix
for i=1,5 do
 mt[i] = {}     -- create a new row
  for j=1,3 do
    mt[i][j] = j
    print(i,j)
    print (mt[i][j])
  end
end

You probably Made a simple typo, but if not, the explanation (as you probably know) is that the function print() is passed the argument mt[i][j], the mt (the variable) is part of the argument too.

Upvotes: 3

Related Questions