Skip to content

Tables

Tables are SamaLang’s primary and only data structure (inherited from Lua). They can function as arrays, dictionaries, records, or objects.

Terminal window
ada data = {}
Terminal window
ada buah = {"apel", "mangga", "jeruk"}
tulis(buah[1]) -- Output: apel
tulis(buah[2]) -- Output: mangga
tulis(buah[3]) -- Output: jeruk
Terminal window
ada mahasiswa = {
nama = "Ahmad",
umur = 20,
jurusan = "Teknik Informatika"
}
tulis(mahasiswa.nama) -- Output: Ahmad
tulis(mahasiswa["umur"]) -- Output: 20
Terminal window
ada buah = {"apel", "mangga", "jeruk"}
-- Bracket notation
tulis(buah[1])
-- Dot notation (for string keys)
ada profil = {nama = "Sari", kota = "Jakarta"}
tulis(profil.nama)
tulis(profil["kota"])
Terminal window
ada buah = {"apel", "mangga"}
-- Add element
buah[3] = "jeruk"
-- Modify element
buah[1] = "pisang"
tulis(buah[1]) -- Output: pisang

Use # to get the number of elements in a sequential table:

Terminal window
ada angka = {10, 20, 30}
tulis(#angka) -- Output: 3
Terminal window
ada buah = {"apel", "mangga", "jeruk"}
untuk i = 1, #buah boat
tulis(buah[i])
jure_mo
Terminal window
ada warna = {"merah", "biru", "hijau"}
untuk i, v in ipairs(warna) boat
tulis(i .. ": " .. v)
jure_mo
Terminal window
ada mahasiswa = {nama = "Ahmad", umur = 20}
untuk k, v in pairs(mahasiswa) boat
tulis(k .. " = " .. tostring(v))
jure_mo

Tables can contain other tables:

Terminal window
ada kelas = {
{nama = "Ahmad", umur = 20},
{nama = "Sari", umur = 21},
{nama = "Budi", umur = 19}
}
tulis(kelas[1].nama) -- Output: Ahmad
tulis(kelas[2].umur) -- Output: 21
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