Lua Tables Patterns
БесплатноБез исполняемых скриптовНе проверенUse when lua tables as the universal data structure including arrays, dictionaries, objects, metatables, object-oriented patterns, data structures, and…
от TheBushidoCollective★ 202 звезды на GitHubОб этом скилле
Lua Tables Patterns
Introduction
Tables are Lua's sole compound data structure, serving as arrays, dictionaries, objects, modules, and more. This versatility makes tables fundamental to Lua programming, enabling implementations of virtually any data structure through creative use of table features and metatables.
Tables use associative arrays that can be indexed with any Lua value except nil and NaN. Array-like tables use consecutive integer indices starting from 1, while dictionary-like tables use arbitrary keys. Metatables enable operator overloading and advanced behaviors.
This skill covers table fundamentals, array and dictionary patterns, metatables, object-oriented programming, common data structures, performance optimization, and idiomatic table manipulation techniques.
Table Fundamentals
Tables combine arrays and hash maps into a single versatile data structure with 1-based indexing.
-- Empty table creation
local t1 = {}
local t2 = table.create(100) -- Pre-allocate (LuaJIT)
-- Array-style tables (consecutive integers from 1)
local array = {10, 20, 30, 40, 50}
print(array[1]) -- 10
print(array[5]) -- 50
print(#array) -- 5 (length operator)
-- Dictionary-style tables (any key type)
local dict = {
name = "Alice",
age = 30,
email = "[email protected]"
}
print(dict.name) -- Dot notation
print(dict["age"]) -- Bracket notation
-- Mixed array and dictionary
local mixed = {
10, 20, 30, -- array part: [1]=10, [2]=20, [3]=30
name = "Bob",
age = 25
}
print(mixed[2]) -- 20
print(mixed.name) -- "Bob"
-- Constructor syntax variations
local point = {x = 10, y = 20}
local point2 = {["x"] = 10, ["y"] = 20} -- Equivalent
-- Nested tables
local nested = {
user = {
name = "Charlie",
address = {
city = "Seattle",
zip = "98101"
}
}
}
print(nested.user.address.city) -- "Seattle"
-- Table insertion and removal
local list = {}
table.insert(list, "first")
table.insert(list, "second")
table.insert(list, 2, "middle") -- Insert at position 2
print(list[1]) -- "first"
print(list[2]) -- "middle"
print(list[3]) -- "second"
local removed = table.remove(list, 2) -- Remove at position 2
print(removed) -- "middle"
-- Table iteration
-- Pairs: All keys (unordered)
for key, value in pairs(dict) do
print(key, value)
end
-- Ipairs: Integer keys in order (1, 2, 3, ...)
for index, value in ipairs(array) do
print(index, value)
end
-- Manual iteration
for i = 1, #array do
print(i, array[i])
end
-- Table copying (shallow)
local original = {1, 2, 3, x = 10}
local copy = {}
for k, v in pairs(original) do
copy[k] = v
end
-- Table concatenation
local fruits = {"apple", "banana", "cherry"}
local str = table.concat(fruits, ", ")
print(str) -- "apple, banana, cherry"
-- Sorting
local numbers = {5, 2, 8, 1, 9}
table.sort(numbers)
-- numbers is now {1, 2, 5, 8, 9}
-- Custom sort
local people = {
{name = "Alice", age = 30},
{name = "Bob", age = 25},
{name = "Charlie", age = 35}
}
table.sort(people, function(a, b)
return a.age < b.age
end)
Tables efficiently combine arrays and hash tables, with the implementation automatically optimizing storage based on usage patterns.
Array Patterns
Lua arrays use 1-based indexing and provide efficient sequential access through the array part of tables.
-- Creating arrays
local empty = {}
local numbers = {10, 20, 30, 40, 50}
local strings = {"hello", "world", "lua"}
-- Array length
print(#numbers) -- 5
-- Appending elements
numbers[#numbers + 1] = 60
table.insert(numbers, 70)
-- Prepending (expensive)
table.insert(numbers, 1, 0)
-- Removing elements
local last = table.remove(numbers) -- Remove and return last
local first = table.remove(numbers, 1) -- Remove and return first
-- Array operations
function map(array, fn)
local result = {}
for i = 1, #array do
result[i] = fn(array[i])
end
return result
end
local doubled = map(numbers, function(x) return x * 2 end)
function filter(array, predicate)
local result = {}
for i = 1, #array do
if predicate(array[i]) then
table.insert(result, array[i])
end
end
return result
end
local evens = filter(numbers, function(x) return x % 2 == 0 end)
function reduce(array, fn, initial)
local accumulator = initial
for i = 1, #array do
accumulator = fn(accumulator, array[i])
end
return accumulator
end
local sum = reduce(numbers, function(acc, x) return acc + x end, 0)
-- Array slicing
function slice(array, start_idx, end_idx)
local result = {}
end_idx = end_idx or #array
for i = start_idx, end_idx do
table.insert(result, array[i])
end
return result
end
local subset = slice(numbers, 2, 4)
-- Array reversal
function reverse(array)
local result = {}
for i = #array, 1, -1 do
table.insert(result, array[i])
end
return result
end
-- In-place reversal
function reverse_in_place(array)
local n = #array
for i = 1, math.floor(n / 2) do
array[i], array[n - i + 1] = arra
Установить Lua Tables Patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл Lua Tables Patterns?
Use when lua tables as the universal data structure including arrays, dictionaries, objects, metatables, object-oriented patterns, data structures, and advanced table manipulation for building flexible, efficient Lua applications.
Как установить скилл Lua Tables Patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Lua Tables Patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic