The Lua Pragramming Language: It's Cool

Geoff Richards

geoff@laxan.com

Features

Types

Syntax: variables

local foo = "stuff"
foo = "other stuff"
print(foo)

Syntax: tables as arrays

local t = { "foo", "bar", "baz" }

print(t[1])   -- indexes start at 1

for idx, value in ipairs(t) do
    print("item number " .. idx ..
          " is " .. value)
end

Syntax: tables as hashes

local t = {
    foo = "string value",
    bar = 23,
    ["foo bar"] = "not identifier",
}

print(t.foo)
print(t["foo bar"])

for key, value in pairs(t) do
    print("key " .. key ..
          " is " .. value)
end

Syntax: functions

function sum (x, y)
    return x + y
end

print(sum(2, 3))

Syntax: closures

function make_counter ()
    local count = 0
    return function ()
        count = count + 1
        return count
    end
end

local counter = make_counter()
print(counter())
print(counter())

print(make_counter()())

Syntax: using modules

local Filter = require "datafilter"

print(Filter.base64_decode("Zm9vYmFy"))

Syntax: defining modules

local M = { _NAME = "simplemaths" }

function M.sum (x, y) return x + y end
function M.mul (x, y) return x * y end

return M

OO features

OO example

local Widget = {}
Widget.__index = Widget

function Widget.new (class, num)
    local self = { num = num }
    setmetatable(self, class)
    return self
end

function Widget:description ()
    return "widget number " .. self.num
end

local mywidget = Widget:new(23)
print(mywidget:description())

Other non-features

Calling C

C function example

static int
my_getenv (lua_State *L) {
    const char *name = luaL_checkstring(L, 1);
    const char *value = getenv(name);

    if (value)
        lua_pushstring(L, value);
    else
        lua_pushnil(L);

    return 1;
}

Embedding in applications