Jordi Pla

Lua Recipes

Basic

Create table:

t = { 'Apple', 'Orange', 'Grapefruit', 'Banana'}

map = { k1 = 'v1', k2 = 'v2', k3 = 'v3' }

Iterate over table:

-- For array-like tables (faster).
for k, v in ipairs(t) do
	print(k, v)
end

-- For map-like and mixed tables.
for k, v in pairs(map) do
	print(k, v)
end

Get table size:

-- # operator for array-like tables.
#t

-- Iterate over the table for map-like tables.
size = 0; for _ in pairs(map) do size = size + 1; end

Swap variables:

x, y = y, x

Run garbage collector:

collectgarbage('collect')

Classes and objects:

local class_method = function(self)
    print('Data: ', self.data)
end

local class_tostring = function(self)
    return '<'..self.data..'>'
end

local class_mt = {
    __tostring = class_tostring;
    __index = {
        method = class_method;
    }
}

-- create a new object
local object = setmetatable({ data = 'data'}, class_mt)
print(object:method())
print(object.data)