ภาพรวม
ฟังก์ชันสำหรับจัดการและดำเนินการกับตารางข้อมูล
ที่อยู่ไฟล์
source/modules/common/table.lua
ฟังก์ชัน
Dump
แปลงตารางเป็น JSON string พร้อมการจัดรูปแบบ
-- ตัวอย่างการใช้งาน
local data = {name = "John", age = 25}
print(AFUCore.Table.Dump(data))
-- {"name": "John", "age": 25}
SizeOf
นับจำนวนสมาชิกในตาราง (nil proof alternative to #table)
-- ตัวอย่างการใช้งาน
local t = {1, nil, 3, nil, 5}
print(AFUCore.Table.SizeOf(t)) -- 3
Set
แปลงตารางเป็น set (ค่าไม่ซ้ำ)
-- ตัวอย่างการใช้งาน
local t = {1, 2, 2, 3, 3, 3}
local set = AFUCore.Table.Set(t)
-- set = {[1] = true, [2] = true, [3] = true}
IndexOf
หาตำแหน่งแรกของค่าในตาราง
-- ตัวอย่างการใช้งาน
local t = {10, 20, 30, 20}
print(AFUCore.Table.IndexOf(t, 20)) -- 2
print(AFUCore.Table.IndexOf(t, 50)) -- -1
LastIndexOf
หาตำแหน่งสุดท้ายของค่าในตาราง
-- ตัวอย่างการใช้งาน
local t = {10, 20, 30, 20}
print(AFUCore.Table.LastIndexOf(t, 20)) -- 4
print(AFUCore.Table.LastIndexOf(t, 50)) -- -1
Find
ค้นหาสมาชิกตัวแรกที่ตรงตามเงื่อนไข
-- ตัวอย่างการใช้งาน
local t = {10, 20, 30, 40}
local result = AFUCore.Table.Find(t, function(v) return v > 25 end)
print(result) -- 30
FindIndex
ค้นหาตำแหน่งแรกที่ตรงตามเงื่อนไข
-- ตัวอย่างการใช้งาน
local t = {10, 20, 30, 40}
local index = AFUCore.Table.FindIndex(t, function(v) return v > 25 end)
print(index) -- 3
Filter
กรองสมาชิกตามเงื่อนไข
-- ตัวอย่างการใช้งาน
local t = {10, 20, 30, 40}
local filtered = AFUCore.Table.Filter(t, function(v) return v > 25 end)
-- filtered = {30, 40}
Map
แปลงค่าสมาชิกทุกตัวตามฟังก์ชันที่กำหนด
-- ตัวอย่างการใช้งาน
local t = {1, 2, 3}
local doubled = AFUCore.Table.Map(t, function(v) return v * 2 end)
-- doubled = {2, 4, 6}
Reverse
กลับลำดับสมาชิกในตาราง
-- ตัวอย่างการใช้งาน
local t = {1, 2, 3}
local reversed = AFUCore.Table.Reverse(t)
-- reversed = {3, 2, 1}
Clone
สร้างสำเนาตาราง (shallow copy)
-- ตัวอย่างการใช้งาน
local t = {x = 1, y = 2}
local clone = AFUCore.Table.Clone(t)
Concat
รวมสองตารางเข้าด้วยกัน
-- ตัวอย่างการใช้งาน
local t1 = {1, 2}
local t2 = {3, 4}
local combined = AFUCore.Table.Concat(t1, t2)
-- combined = {1, 2, 3, 4}
Join
รวมสมาชิกในตารางเป็นสตริงด้วยตัวคั่น
-- ตัวอย่างการใช้งาน
local t = {"a", "b", "c"}
print(AFUCore.Table.Join(t, ", ")) -- "a, b, c"
Sort
เรียงลำดับตารางตามฟังก์ชันที่กำหนด
-- ตัวอย่างการใช้งาน
local t = {3, 1, 4, 1, 5}
AFUCore.Table.Sort(t, function(t, a, b) return a < b end)
-- t = {1, 1, 3, 4, 5}
Copy
สร้างสำเนาตารางแบบลึก (deep copy)
-- ตัวอย่างการใช้งาน
local t = {x = {y = 2}}
local copy = AFUCore.Table.Copy(t)
หมายเหตุ
ฟังก์ชันส่วนใหญ่ไม่เปลี่ยนแปลงตารางต้นฉบับ (ยกเว้น Sort)
Clone ทำ shallow copy, Copy ทำ deep copy