Array

คุณสามารถสร้าง Array ได้โดยใช้ฟังก์ชัน NS.array(tbl) ซึ่งจะรับ table แบบ array และคืนค่ากลับมาเป็น Array Prototype ที่สามารถใช้งานได้คล้าย JavaScript Array เช่น .push(), .map(), การเข้าถึงค่าด้วย [] และอื่น ๆ
local arr = NS.array({ 1, 2, 3 })
print(arr[1]) -- 1

arr:push(4)
print(arr[4]) -- 4

arr[2] = 999
print(arr[2]) -- 999

รายชื่อเมธอดที่รองรับ

MethodDescription
arr:len()คืนค่าความยาวของ array
arr:push(value)เพิ่มค่าที่ท้าย array
arr:pop()ดึงค่าออกจากท้าย array
arr:shift()ดึงค่าออกจากหัว array
arr:unshift(val)เพิ่มค่าที่หัว array
arr:forEach(fn)ทำงานกับทุกค่าด้วย callback
arr:map(fn)สร้าง array ใหม่จากการแปลงค่าทั้งหมด
arr:filter(fn)สร้าง array ใหม่เฉพาะค่าที่ผ่านเงื่อนไข
arr:find(fn)คืนค่าตัวแรกที่ผ่านเงื่อนไข
arr:includes(v)ตรวจสอบว่ามีค่าดังกล่าวอยู่ใน array หรือไม่
arr:indexOf(v)คืน index ของค่าที่ค้นหา (ถ้าไม่มี = -1)
arr:toTable()แปลงกลับเป็น table ปกติของ Lua
arr:print()แสดงค่าทั้งหมดใน array

การใช้งานจริง

local arr = NS.array({ "apple", "banana", "cherry" })

arr:forEach(function(item, index)
    print(index, item)
end)

local filtered = arr:filter(function(item)
    return item ~= "banana"
end)

filtered:print()

Annotation (สำหรับใช้งานร่วมกับ Lua Language Server)

--- @class ArrayPrototype
--- @field len fun(self: ArrayPrototype): integer
--- @field push fun(self: ArrayPrototype, value: any)
--- @field pop fun(self: ArrayPrototype): any
--- @field shift fun(self: ArrayPrototype): any
--- @field unshift fun(self: ArrayPrototype, value: any)
--- @field forEach fun(self: ArrayPrototype, callback: fun(value: any, index: integer))
--- @field map fun(self: ArrayPrototype, callback: fun(value: any, index: integer): any): ArrayPrototype
--- @field filter fun(self: ArrayPrototype, callback: fun(value: any, index: integer): boolean): ArrayPrototype
--- @field find fun(self: ArrayPrototype, callback: fun(value: any, index: integer): boolean): any
--- @field includes fun(self: ArrayPrototype, value: any): boolean
--- @field indexOf fun(self: ArrayPrototype, value: any): integer
--- @field toTable fun(self: ArrayPrototype): any[]
--- @field print fun(self: ArrayPrototype)