View Single Post
08-26-16, 06:24 PM   #3
Lombra
A Molten Giant
 
Lombra's Avatar
AddOn Author - Click to view addons
Join Date: Nov 2006
Posts: 554
Hi!

Lua Code:
  1. function HelloWorld()
  2.   a = {{1,2,3}, {4,5,6}, {7,8,9}}
  3.   m = print (#a);
  4.  
  5.   for i=0,3,1
  6.   do  
  7.     print(a[1]);
  8.  
  9.   end
  10. end

Didn't understand if you have any issues with this example, but the loop doesn't really do anything here, since you don't use the incrementor and instead just print the same first element (Lua tables start on 1) of table a for all four iterations of the loop. That element happens to be another table, and when you print that using the function with the same name, you will just get the table's memory address or some such thing, which isn't really useful for anything.

Using variables as the upper for loop limit is fine. The problem here should that you use 0 as the lower limit, and since Lua tables start at 1 (and you haven't explicitly added an element at index 0) the very first iteration will error and halt the execution. I'm guessing you don't have Lua errors enabled, which would've helped spotting this error!

Code:
/console scriptErrors 1
Once you get the loop working, it's just a matter of adding another loop inside the first one to iterate over the deepest tables.

You may also use ipairs (for "arrays") or pairs (for when arbitrary keys are used) to have some of the work done for you.

Code:
a = {{1,2,3}, {4,5,6}, {7,8,9}}
for i = 1, #a do
	local v = a[i]
	print(v)
end
Code:
a = {{1,2,3}, {4,5,6}, {7,8,9}}
for i, v in ipairs(a) do
	print(v)
end
As far as arrays go, these two examples are functionally identical.
__________________
Grab your sword and fight the Horde!
  Reply With Quote