HOW-TO: tables and array's
 

News:

29 December 2022 - PtokaX 0.5.3.0 (20th anniversary edition) released...
11 April 2017 - PtokaX 0.5.2.2 released...
8 April 2015 Anti child and anti pedo pr0n scripts are not allowed anymore on this board!
28 September 2015 - PtokaX 0.5.2.1 for Windows 10 IoT released...
3 September 2015 - PtokaX 0.5.2.1 released...
16 August 2015 - PtokaX 0.5.2.0 released...
1 August 2015 - Crowdfunding for ADC protocol support in PtokaX ended. Clearly nobody want ADC support...
30 June 2015 - PtokaX 0.5.1.0 released...
30 April 2015 Crowdfunding for ADC protocol support in PtokaX
26 April 2015 New support hub!
20 February 2015 - PtokaX 0.5.0.3 released...
13 April 2014 - PtokaX 0.5.0.2 released...
23 March 2014 - PtokaX testing version 0.5.0.1 build 454 is available.
04 March 2014 - PtokaX.org sites were temporary down because of DDOS attacks and issues with hosting service provider.

Main Menu

HOW-TO: tables and array's

Started by plop, 24 March, 2004, 23:10:53

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

plop

like all the other howto's were again gone need the lua command line for the examples.

in C/C++ there are tables and array's, in lua the array's are also tables.
array = { "string1", "string2", "string3", "string4", "string5" }
table = { [1]="string1", [2]="string2", [3]="string3", [4]="string4", [5]="string5" }
the table shown here is called an associative table as the thing before the = is associated with the part after it.
now most ppl would expect that i'm gone start with explaining the array's, I'm not gone do that.
as array's are tables to it's easyer to 1st explain the tables, you'll then easyer see the link between those to.
the table i made uses numbers as indexes (key's) and strings as value's.

----- chapter 1: tables.

were gone start real easy by just printing out all the value's in the table.
i used numbers as key's we can retrieve them with this: table[number].
lets do a simple loop.

print("example 1")
table = { [1]="string1", [2]="string2", [3]="string3", [4]="string4", [5]="string5" }

for index = 1,5 do --- do a loop of 5 steps.
   print(table[index])
end

now this worked fine but you can allready see a problem, what if there would be more key's in the table??
indeed those wouldn't be printed, so we need a different kind of loop.

print("example 2")
table = { [1]="string1", [2]="string2", [3]="string3", [4]="string4", [5]="string5" }

for key,value in table do --- do a loop for aslong as there are key's with value's in the table.
   print(table[key])
end

this way opens up another way, we can also grab the key from the table, which can be handy sometimes to have.
the loop states that there is a key and a value, we can use them direct.
lets print the matching key now along with the value.

print("example 3")
table = { [1]="string1", [2]="string2", [3]="string3", [4]="string4", [5]="string5" }

for key,value in table do --- do a loop for aslong as there are key's with value's in the table.
   print("key= "..key.." and has the value: ".. value)
end

now we know how to proces a table so lets start with stuffing things into it.
adding things is really simple, table[6]="string6".
can't make it more complex then this, or can i??
yes I can, as i'm lazy were gone use a loop to extend the table to hold 10 key's/value's.
to show the new table the same loop from the last example is gone be fine to use.

print("example 4")
table = { [1]="string1", [2]="string2", [3]="string3", [4]="string4", [5]="string5" }

for index=6,10 do  -- start a loop from 5 steps starting with index number 6.
   table[index]="string"..index
end
-- next execute the loop from the last example.
for key,value in table do --- do a loop for aslong as there are key's with value's in the table.
   print(table[key])
end

now lets do the opposite of adding things to the table, were gone remove key's 1 to 5.
a table can hold everything BUT nil, so all we have to do it declare the key's to be nil.
table[1]=nil.
were gone extend the last example with a loop to do this.

print("example 5")
table = { [1]="string1", [2]="string2", [3]="string3", [4]="string4", [5]="string5" }

for index=1,5 do -- start a loop of 5 steps starting with 1.
   table[index]=nil
end

for index=6,10 do  -- start a loop from 5 steps starting with index number 6.
   table[index]="string"..index
end
-- next execute the loop from the last example.
for key,value in table do --- do a loop for aslong as there are key's with value's in the table.
   print(table[key])
end

now you might see something weird happend (not on every1 tho).
string8
string9
string10
string6
string7

the order is messed up, but no reason to panic at all.
this isn't a problem, this is just how lua works.
when we remove things we get a free wasted space, this is filled by moving something else to it.
but do remember this, your gone see the same on array's and there it can cause problems.
but before were gone discus that were gone do something the smartasses have allready seen.
the 1st loop removes key's 1 to 5, this is the full table.
so instead of wasting time on the loop we could drop the full table in the garbage bin and declare a new empty table.
this is nearly the same as removing a key, table = nil drops the table and table = {} builds a new.
lets do a example again.

print("example 6")
table = { [1]="string1", [2]="string2", [3]="string3", [4]="string4", [5]="string5" }

table = nil
table = {}

for index=6,10 do  -- start a loop from 5 steps starting with index number 6.
   table[index]="string"..index
end
-- next execute the loop from the last example.
for key,value in table do --- do a loop for aslong as there are key's with value's in the table.
   print(table[key])
end

now we basicly finished the table part (there are some other way to adress them but not gone discus those here).

plop
http://www.plop.nl lua scripts/howto\'s.
http://www.thegoldenangel.net
http://www.vikingshub.com
http://www.lua.org

>>----> he who fights hatred with hatred, drives the spreading of hatred <----<<

plop

----- chapter 2: array's.

allready told you that array's are tables to, now let me explain how that is posible.
for us humans a array looks like this: array = { "string1", "string2", "string3", "string4", "string5" }.
but lua sees it as array = { [1]="string1", [2]="string2", [3]="string3", [4]="string4", [5]="string5" }.
as you can see lua uses indexes for them to, but we never see them in the array.
this makes it all a bit spooky, and as a result you might think that it works the same as a associative table but no.
array's have there own methods and they can cause big problems if you use them incorrect, the example's are gone show all those things.
lets start with just showing all the value's in the array 1 by 1.

print("example 6")
array = { "string1", "string2", "string3", "string4", "string5" }

for index=1,5 do
   print(array[index])
end

now this looks exactly the same as the table version.
you can allready start to see that tables and array's are the same in lua.
on example to we changed the loop so it would work even if the table held more then 5 things.
to make the link between array's and tables totaly clear were gone use the code from example to again.

print("example 7")
array = { "string1", "string2", "string3", "string4", "string5" }

for key,value in array do
   print(array[key])
end

as you can see it works fine, but it's not a nice way of doing it (should be avoided if posible).
specialy if you think that array's have a trick up there sleave which could be used here.
getn(array) returns the amount of value's stored in the array.
lets use take the code from example 6 but insert getn.

print("example 8")
array = { "string1", "string2", "string3", "string4", "string5" }

print("the array has "..getn(array).." value's stored in it")

for index=1,getn(array) do -- start a loop starting with 1 and ending with the highest key stored in the array
   print(array[index])
end

now were getting to the hard part, adding removing things to/from the array.
you might do it the same way as with tables and it's gone work untill a certain point.
the reason for this is that lua excepts all types of things in a single table.
mixedtable = { "string", [1]="string", ["string"]=2, [15]= function(user, data) dosomething end, table2={1,2,3} }.
as you can see on the above line you mixs all sorts, lua won't complain at all.
but getn works only correct on a true array, so think carefull about it before you try to do sutch a thing.
now because of this lua has some special commands 2 insert and remove things from a array, tinsert and tremove.
the t comes from table.
now lets look at tinsert to start with.
tinsert(array [,position] , value)
the position is something new for us and is optional, if you leave it away it's gone insert the value's at the end of the array.
if you use it it's gone place it on the matching position, more about this later on.
lets take a look at a example based on the previous example, again were gone insert 5 strings.

print("example 9")
array = { "string1", "string2", "string3", "string4", "string5" }

print("the array has "..getn(array).." value's stored in it")

for index=6,10 do
   tinsert(array, "string"..index)
end

print("now the array has "..getn(array).." value's stored in it")

for index=1,getn(array) do -- start a loop starting with 1 and ending with the highest key stored in the array
   print(array[index])
end

as you can see the strings are added to the array and are in the right order.
getn is automaticly updated to the new amount of value's stored in the array (the value getn returns is actualy stored in the array to on the last

not used space).
now lets try to remove the first 5 strings by using the same kind of loop we used on removing things from the table in example 5.

-- ex 10
print("example 10")
array = { "string1", "string2", "string3", "string4", "string5", "string6", "string7", "string8", "string9", "string10" }

print("the array has "..getn(array).." value's stored in it")

for index=1,5 do
   tremove(array, index)
end

print("now the array has "..getn(array).." value's stored in it")

for index=1,getn(array) do -- start a loop starting with 1 and ending with the highest key stored in the array
   print(array[index])
end

now it's about time to panic, has lua lost it's mind ???
the array has 10 value's stored in it
now the array has 5 value's stored in it
string2
string4
string6
string8
string10
what was removed were not the fist 5 but every odd number, whats going on here??
the answer is simple.
string1 has index 1, but when we remove that string2 gets the index 1.
after every insert/remove the key's are updated.
to solve this we can do a couple tricks.
lets start simple by just keeping removing index number 1 5 times.

-- ex 11
print("example 11")
array = { "string1", "string2", "string3", "string4", "string5", "string6", "string7", "string8", "string9", "string10" }

print("the array has "..getn(array).." value's stored in it")

for index=1,5 do
   tremove(array, 1)
end

print("now the array has "..getn(array).." value's stored in it")

for index=1,getn(array) do -- start a loop starting with 1 and ending with the highest key stored in the array
   print(array[index])
end

now this works fine but what if we just want to remove the indexes 3, 5, 7 and 9.
we can't use a loop here and we can't just remove them in the given order??
the trick is to work backwards, if we first remove index 9 then 10 becomes 9 but 7 stays 7.
lets take a look at it.

-- ex 12
print("example 12")
array = { "string1", "string2", "string3", "string4", "string5", "string6", "string7", "string8", "string9", "string10" }

print("the array has "..getn(array).." value's stored in it")

tremove(array, 9)
tremove(array, 7)
tremove(array, 5)
tremove(array, 3)

print("now the array has "..getn(array).." value's stored in it")

for index=1,getn(array) do -- start a loop starting with 1 and ending with the highest key stored in the array
   print(array[index])
end

that worked, now lets take a step back to example 10.
why ?? because it could have worked if we would have done what we just learned.
if we run the loop backwards it's gone works perfectly.

print("example 13")
array = { "string1", "string2", "string3", "string4", "string5", "string6", "string7", "string8", "string9", "string10" }

print("the array has "..getn(array).." value's stored in it")

for index=5,1, -1 do -- start a loop begining with 5 and counting backwars to 1, the -1 tells the loop to count backwards
   tremove(array, index)
end

print("now the array has "..getn(array).." value's stored in it")

for index=1,getn(array) do -- start a loop starting with 1 and ending with the highest key stored in the array
   print(array[index])
end

as you can see the result is now just what we wanted, the first 5 value's are gone.
now lets take a closer look at tinsert again but now with position number.
gone make it a bit harder now as were gone fix the broken array from example 10, and by abusing the re-indexing.
were gone use the same backwards loop and lets see what is gone happen.

print("example 14")
array = { "string2", "string4", "string6", "string8", "string10" }

print("the array has "..getn(array).." value's stored in it")

for index=5,1, -1 do -- start a loop begining with 5 and counting backwars to 1, the -1 tells the loop to count backwards
   tinsert(array, index, "string"..index)
end

print("now the array has "..getn(array).." value's stored in it")

for index=1,getn(array) do -- start a loop starting with 1 and ending with the highest key stored in the array
   print(array[index])
end

nearly correct, they are on the right place just the strings are wrong.
logical as we used the index from the loop.
lets fix this to end this howto.

print("example 15")
array = { "string2", "string4", "string6", "string8", "string10" }

print("the array has "..getn(array).." value's stored in it")

number = 9 -- declaring number to be 9 as it's the first string number were gone need
for index=5,1, -1 do -- start a loop begining with 5 and counting backwars to 1, the -1 tells the loop to count backwards
   tinsert(array, index, "string"..number)
   number = number - 2 -- subtracting number by 2 as we need to skip all even numbers
end

print("now the array has "..getn(array).." value's stored in it")

for index=1,getn(array) do -- start a loop starting with 1 and ending with the highest key stored in the array
   print(array[index])
end
now the array is fixed in a nice orderly way like it was on the start of example 10.

i hope you enjoyed it and learned to master tables and array's.
happy scripting.

plop
http://www.plop.nl lua scripts/howto\'s.
http://www.thegoldenangel.net
http://www.vikingshub.com
http://www.lua.org

>>----> he who fights hatred with hatred, drives the spreading of hatred <----<<

R2??

Very nice work, as usual.. :)

plop

QuoteOriginally posted by R2??
Very nice work, as usual.. :)
thx for the compliment and thx again for pre-reading it.

plop
http://www.plop.nl lua scripts/howto\'s.
http://www.thegoldenangel.net
http://www.vikingshub.com
http://www.lua.org

>>----> he who fights hatred with hatred, drives the spreading of hatred <----<<

HaArD

Thanks for these PLOP! They are great, and have really helped me learn LUA's syntaxes etc. :)

Corayzon

really nice work plop...im printing this one out for sure!

keep it up dude

plop

http://www.plop.nl lua scripts/howto\'s.
http://www.thegoldenangel.net
http://www.vikingshub.com
http://www.lua.org

>>----> he who fights hatred with hatred, drives the spreading of hatred <----<<

Skrollster

If it is ok, i'll translate this to swedish and then add the things i think are missing to both your and mine version... (english and swedish) and publish the swedish one @ //www.directconnect.se

plop

QuoteOriginally posted by Skrollster
If it is ok, i'll translate this to swedish and then add the things i think are missing to both your and mine version... (english and swedish) and publish the swedish one @ //www.directconnect.se
yep i left some things out on purpose.
chapter 2 is allready a bit complex, so thought it might be better 2 leave some things out.
don't know what you think is missing, but if you tell me i'll add them or use your stuff.
got no problem with it if you post it on other forums, also want 2 add them 2 my own website so pls place a link 2 that.

plop
http://www.plop.nl lua scripts/howto\'s.
http://www.thegoldenangel.net
http://www.vikingshub.com
http://www.lua.org

>>----> he who fights hatred with hatred, drives the spreading of hatred <----<<

kepp

That would be very appreciated Skrollster.. And thanks alot plop for making such a nice ( HowTo )

It helped me with a few things that i've been struggeling about for a loong time..
Guarding    

PLAstic

QuoteOriginally posted by plop
like all the other howto's were again gone need the lua command line for the examples.

----- chapter 1: tables.
----- chapter 2: array's.

  Nice, but it's very simple examples. How can I append new item in array that have some values? By example,
we have next array:
tItems={
{"FirstName","LastName","Age"},
{"FirstName2","LastName2","Age2"},
};

I need to append next item at the end of array:

{"FirstName3","LastName3","Age3"}

How can I do it?

NightLitch

Try this one out:

tinsert(tItems, {firstname,lastname,age}}

/NL
//NL

plop

QuoteOriginally posted by PLAstic Nice, but it's very simple examples. How can I append new item in array that have some values? By example,
we have next array:
tItems={
{"FirstName","LastName","Age"},
{"FirstName2","LastName2","Age2"},
};

I need to append next item at the end of array:

{"FirstName3","LastName3","Age3"}

How can I do it?
you are here using a array with in that array's, also called nested array/table.
here's a addon 2 the howto, could be the start of chapter 3.
tItems={
   {"FirstName","LastName","Age"},
   {"FirstName2","LastName2","Age2"}
}

print("lets first print the nested array")
for i=1,getn(tItems) do
   line = ""
   for j=1,getn(tItems[i]) do
      line = line.." "..tItems[i][j]
   end
   print(line)
end

print("time to insert another array")
tToInsert = {"FirstName3","LastName3","Age3"}

tinsert(tItems, tToInsert)
print("now lets print the nested array again")
for i=1,getn(tItems) do
   line = ""
   for j=1,getn(tItems[i]) do
      line = line.." "..tItems[i][j]
   end
   print(line)
end
tinsert needs minimal 2 arguments.
1) the array which you wanne proces.
2) the stuff you wanne insert into it.
but it can handle a 3de argument.
3) location number.
if you leave out number 3 it will always insert @ the end.

plop
http://www.plop.nl lua scripts/howto\'s.
http://www.thegoldenangel.net
http://www.vikingshub.com
http://www.lua.org

>>----> he who fights hatred with hatred, drives the spreading of hatred <----<<

SMF spam blocked by CleanTalk