61 posts / categories / feed

Basic Lua Programming With For Loops

Creating and Accessing Table with For Loops

Note when working with pairs and associative indexes, the order is unpredictable, hence you will have to write some logic to put it in order yourself.

You can use “ipairs” to access the table.

-- example some items in my shopping cart
local cart = {
    "Pie",
    "Cheese",
    "Noodles",
    drink = "Coke",
    fruits = {
	"Pear",
	"Apple"
    }
}

-- iterate increment through cart
for i=1, #cart do
    print(cart[i]);
end

-- iterate decrement through cart
for i=#cart, 1, -1 do
    print(cart[i]);
end

-- using ipairs
for key, value in ipairs(cart) do
    print(value);
end

for key, value in ipairs(cart) do
    print(key, value);
end

-- accessing the associative indexes, getting the key and fruits
for key, value in ipairs(cart.fruits) do
    print(key, value);
end

-- to access the values of the associative index, getting the fruits name
for key, value in ipairs(cart.fruits) do
    print(cart.fruits[key]);
end