Tables
Tables are SamaLang’s primary and only data structure (inherited from Lua). They can function as arrays, dictionaries, records, or objects.
Creating Tables
Section titled “Creating Tables”Empty Table
Section titled “Empty Table”ada data = {}Array (Sequential Keys)
Section titled “Array (Sequential Keys)”ada buah = {"apel", "mangga", "jeruk"}
tulis(buah[1]) -- Output: apeltulis(buah[2]) -- Output: manggatulis(buah[3]) -- Output: jerukDictionary (Key-Value Pairs)
Section titled “Dictionary (Key-Value Pairs)”ada mahasiswa = { nama = "Ahmad", umur = 20, jurusan = "Teknik Informatika"}
tulis(mahasiswa.nama) -- Output: Ahmadtulis(mahasiswa["umur"]) -- Output: 20Accessing Elements
Section titled “Accessing Elements”ada buah = {"apel", "mangga", "jeruk"}
-- Bracket notationtulis(buah[1])
-- Dot notation (for string keys)ada profil = {nama = "Sari", kota = "Jakarta"}tulis(profil.nama)tulis(profil["kota"])Modifying Tables
Section titled “Modifying Tables”ada buah = {"apel", "mangga"}
-- Add elementbuah[3] = "jeruk"
-- Modify elementbuah[1] = "pisang"
tulis(buah[1]) -- Output: pisangTable Length
Section titled “Table Length”Use # to get the number of elements in a sequential table:
ada angka = {10, 20, 30}tulis(#angka) -- Output: 3Iterating Over Tables
Section titled “Iterating Over Tables”Numeric For Loop
Section titled “Numeric For Loop”ada buah = {"apel", "mangga", "jeruk"}
untuk i = 1, #buah boat tulis(buah[i])jure_moGeneric For with ipairs (Sequential)
Section titled “Generic For with ipairs (Sequential)”ada warna = {"merah", "biru", "hijau"}
untuk i, v in ipairs(warna) boat tulis(i .. ": " .. v)jure_moGeneric For with pairs (All Keys)
Section titled “Generic For with pairs (All Keys)”ada mahasiswa = {nama = "Ahmad", umur = 20}
untuk k, v in pairs(mahasiswa) boat tulis(k .. " = " .. tostring(v))jure_moNested Tables
Section titled “Nested Tables”Tables can contain other tables:
ada kelas = { {nama = "Ahmad", umur = 20}, {nama = "Sari", umur = 21}, {nama = "Budi", umur = 19}}
tulis(kelas[1].nama) -- Output: Ahmadtulis(kelas[2].umur) -- Output: 21Common Table Functions
Section titled “Common Table Functions”| Function | Description | Example |
|---|---|---|
table.insert(t, pos, val) |
Insert at position | table.insert(buah, 2, "mangga") |
table.remove(t, pos) |
Remove at position | table.remove(buah, 1) |
table.sort(t) |
Sort alphabetically | table.sort(buah) |
ipairs(t) |
Iterator for arrays | for i, v in ipairs(t) boat |
pairs(t) |
Iterator for all keys | for k, v in pairs(t) boat |