Difference between revisions of "Basic lua: Tables"

From The Official Visionaire Studio: Adventure Game Engine Wiki
Line 11: Line 11:
 
! method 1: automatically generated index values !!
 
! method 1: automatically generated index values !!
 
|-
 
|-
| style="max-width:700px;" | <syntaxhighlight>
+
| style="max-width:680px;" | <syntaxhighlight lang="lua">
 
local t = {1, 2, 3, 4, 5, "six", 7, "ate", 9} -- automatically assigns an index number to each value starting from 1.
 
local t = {1, 2, 3, 4, 5, "six", 7, "ate", 9} -- automatically assigns an index number to each value starting from 1.
  
 
print( "index total = " .. #(t) ) -- print total of table entries
 
print( "index total = " .. #(t) ) -- print total of table entries
  
for i = 1, table.maxn(t) do -- for 1 to table total, print value of index number
+
for i = 1, #t do -- for 1 to table total, print value of index number
 
  print( t[i] )
 
  print( t[i] )
 
end
 
end
Line 26: Line 26:
 
! method 2: manually created index values !!
 
! method 2: manually created index values !!
 
|-
 
|-
| style="max-width:700px;" | <syntaxhighlight>
+
| style="max-width:680px;" | <syntaxhighlight lang="lua">
local t = {} -- empty table
+
local t = {
t[1] = 1
+
 
t[2] = "two"
+
[1] = 1
t[3] = 3
+
[2] = "two"
t[4] = 2 * 2
+
[3] = 3
t[5] = "five"
+
[4] = 2 * 2
 +
[5] = "five"
 +
 
 +
}
  
 
print( "index total = " .. #(t) ) -- print total of table entries
 
print( "index total = " .. #(t) ) -- print total of table entries
  
for i = 1, table.maxn(t) do -- for 1 to table total, print value of index number
+
for i = 1, #t do -- for 1 to table total, print value of index number
 
  print( t[i] )
 
  print( t[i] )
 
end
 
end
 
</syntaxhighlight> || width="200px" | [[File:lb_tables_002.png|thumb|right|180px|click to enlarge]]
 
</syntaxhighlight> || width="200px" | [[File:lb_tables_002.png|thumb|right|180px|click to enlarge]]
 
|}{{toc}}
 
|}{{toc}}

Revision as of 18:43, 2 September 2022

Tables are one of the features of Lua script, that make the scripting language so dynamic & easy to use, as they allow us to easily create tables, insert, remove & sort data. Tables are often comprised of arrays that usually involve keywords - or an index number - & a value. Tables can be accessed using multiple different methods.

< Index >

Creating a table

method 1: automatically generated index values
local t = {1, 2, 3, 4, 5, "six", 7, "ate", 9} -- automatically assigns an index number to each value starting from 1.

print( "index total = " .. #(t) ) -- print total of table entries

for i = 1, #t do -- for 1 to table total, print value of index number
 print( t[i] )
end
click to enlarge
method 2: manually created index values
local t = {

[1] = 1
[2] = "two"
[3] = 3
[4] = 2 * 2
[5] = "five"

}

print( "index total = " .. #(t) ) -- print total of table entries

for i = 1, #t do -- for 1 to table total, print value of index number
 print( t[i] )
end
click to enlarge