View Single Post
08-16-05, 06:56 AM   #4
Littlejohn
A Warpwood Thunder Caller
AddOn Author - Click to view addons
Join Date: Jun 2005
Posts: 90
Originally Posted by Garoun
P.S. In lua are the variables of this nature considered 'Arrays' or 'Tables'?
Lua doesn't have arrays -- it's tables all the way down.

There is a special table property named "n" though that the pseudo-array features use as the last index. The functions table.insert, table.remove, and table.getn won't work right without "n" defined. If you want array behavior, you should use these functions to build your table.

If it's awkward to build your table that way, you can call table.setn to change the last index. Be careful doing that though because Lua doesn't care if the table contents and "n" are consistent (you could over-write data in the table).

Here are tables acting like arrays:
Code:
-- no keys, so Lua automatically uses 1,2,3 for keys and getn=3
t = { 'a', 'b', 'c' }

table.insert(t, 'd')

for i=1,table.getn(t) do
  print(t[i])
end

-- if you give any keys, you should give all the keys, otherwise Lua
-- will use keys starting with 1 and those probably won't fit in with
-- the keys you use. getn will be screwed up too.
t = { [5] = 'a', [10] = 'b', [15] = 'c' }

-- now set "n" to the last index (not the table size!)
table.setn(t, 15)

for i=1,table.getn(t) do
  print(t[i])
end

-- the following is a "normal" table loop and hits only the defined
-- table entries in a random order.
for k,v in t do
  print(k,v)
end
  Reply With Quote