Table API

From ComputerCraft
Jump to: navigation, search
FunctionFunctiontable.concat
Turn table into a string, provided that all of its elements can be coerced into a string. If a separator is specified, then it is inserted between each element. Additionally, concatenation starts at the ith element and ends at the jth.
Syntax table.concat()
Returns string
Part of Lua (source)
API table
ExampleExampleConcat an array of numbers
Since numbers are coercible to strings, an array of numbers can be concatenated.
Code
print(table.concat({ 1, 2, 3 }, ', '))
Output
1, 2, 3
ExampleExampleConcat a slice of an array
Concatenates an array of both strings and numbers, starting from the 3rd element up to the 5th.
Code
print(table.concat({ 1, 2, 3, "a", "b", 4, 5 }, ' ', 3, 5))
Output
3 a b


FunctionFunctiontable.foreach
This function is deprecated.[1]

Calls func once for each key-value pair in the tbl. Specifically,

table.foreach(tbl, func)

is equivalent to

for key, value in pairs(tbl) do
  if func(key, value) ~= nil then
    break
  end
end
Syntax table.foreach()
Returns nil
Part of Lua (source)
API table
ExampleExamplePrint the elements of a table
Print out each key-value pair in tbl.
Code
local tbl = { a = 1, b = 2, 'foo', 'bar' }
table.foreach(tbl, function(k, v)
  print(k, v)
end)
Output
a 1
b 2
1 foo
2 bar


References

Table.foreachi Table.insert Table.pack Table.remove

FunctionFunctiontable.sort
Sort the array, using the function sorter to compare the elements, or < if it is not given, in place. If no sorter is specified, the array must consist entirely of comparable values (either numbers or strings, but not both).
Syntax table.sort()
Returns nil
Part of Lua (source)
API table
ExampleExampleSort an array
Print a sorted version of the array, which is turned into a string using table.concat.
Code
t = { 5, 4, 2, 1, 3 }
table.sort(t)
print(table.concat(t, ', '))
Output
1, 2, 3, 4, 5
ExampleExampleFind the smallest element in an array of random numbers
Instead of using a for loop to find the smallest element in an array, it is possible to sort and then index it. The first index will be the smallest element.
Code
local elements = 10
local array = {}
for i = 1, elements do
  array[i] = math.random(1, 1000)
end
table.sort(array)
print(array[i])
Output The smallest number in array, which depends on how the array was filled.
ExampleExampleSort an array of tables by their length
This demonstrates using a custom sorter function to compare tables by their length. Note that generally < will not compare tables.
Code
local array = { { 'foo', 'bar', 'baz' }, { 'red', 'green', 'blue' }, { 'apple', 'orange' } }
table.sort(array, function(a, b)
  return #a < #b
end)
print(array[1][1])
Output
'apple'