ข้ามไปเนื้อหา

มอดูล:array/documentation

จาก วิกิพจนานุกรม พจนานุกรมเสรี

นี่คือหน้าเอกสารการใช้งานสำหรับ มอดูล:array

Returns an array constructor that produces a table that has a number of functions available as methods: the table library functions, and various vanilla Lua functions and functions from Module:table and Module:fun that operate on arrays or on tables with integer keys.

local Array = require("Module:array")
local nums = Array() -- or Array:new()
nums:type() --> "array"
for i = 1, 5 do
	nums:insert(i)
end
nums:concat(", ") --> "1, 2, 3, 4, 5"

local squares = nums:map(function (num) return num ^ 2 end) -- Returns new array.
squares:concat(', ') --> "1, 4, 9, 16, 25"

local even_squares = squares:filter(function (square) return square % 2 == 0 end)
even_squares:concat(", ") --> "4, 16"

The functions from Module:table and Module:fun are loaded as needed.

Functions from Module:table:

  • compressSparseArray (alias compress), contains, invert, isArray, length, listToSet (alias toSet), maxIndex, numKeys, removeDuplicates, reverse, reverseIpairs, serialCommaJoin, sparseIpairs

Functions from Module:fun. These have a function as the second argument:

  • all, filter, map, some

These functions are included in a funcs subtable of an array (awkward):

  • affixNums, keysToList, numKeys

The following functions return an array (with the array metatable):

  • affixNums, compressSparseArray, keysToList, numKeys, removeDuplicates, reverse

The names with underscores instead of camel case can be used as aliases: for instance, arr:to_set() instead of arr:toSet().

The array constructor behaves differently depending on the arguments supplied to it. Without arguments, it creates an empty table. Given a single table, it adds the metatable to it. If the table has been loaded with mw.loadData, it duplicates the table, removing the metatable that is found in tables loaded with mw.loadData. Otherwise, it creates a new table (array) containing the arguments.

The array constructor does this by adding a metatable. This is similar to how all strings have a metatable that allows the string library functions to be used as methods: for instance, ("abc"):sub(1, 1) for string.sub("abc", 1, 1).