lua: Simple but yet powerfull script language

[top]

  1. Simple embedded oriented language.
  2. Extensible by using simple "fallback" mechanism.
  3. Example: Cross referencer

    #!/usr/local/bin/lua
    
    -- Tiny cross referencer written in Lua
    
    name = "([A-Za-z_][A-Za-z0-9_]*)"
    
    xref = {}
    linno = 0
    
    -- return all keys in table t
    function keys(t)
        local ret = {}
        local i = 1
        local var, val = next(t, nil)
        while var do
            ret[i] = var;
            i = i + 1
            var, val = next(t, var)
        end
        return ret
    end
    
    -- return the last index + 1 of table t
    function nxt(t)
        local i = 1
        while t[i] do
            i = i + 1
        end
        return i
    end
    
    -- compare strings ignoring cases
    function icomp(a, b)
        if a == b then
            return 0
        end
        local la = strlower(a)
        local lb = strlower(b)
        if la < lb then
            return -1
        end
        return 1
    end
    
    -- quick sort
    function qsort(t, left, right)
        if left >= right then
            return
        end
        local last = left
        local i = left + 1
        while i <= right do
            if icomp(t[i], t[left]) < 0 then
                last = last + 1
                local tmp = t[last]
                t[last] = t[i]
                t[i] = tmp
            end
            i = i + 1
        end
        local tmp = t[left]
        t[left] = t[last]
        t[last] = tmp
        qsort(t, left, last-1)
        qsort(t, last+1, right)
    end
    
    -- sort a table t
    function sort(t)
        qsort(t, 1, nxt(t) - 1)
        return t
    end
    
    -- pass 1
    line = read("[^\n]*{\n}")
    while line do
        linno = linno + 1
        while strlen(line) > 0 do
            s, e, id  = strfind(line, name)
            if s then
                if xref[id] then
                    local n = nxt(xref[id])
    		if xref[id][n - 1] ~= linno then
    	            xref[id][n] = linno
                    end
                else
                    xref[id] = { linno }
                end
                line = strsub(line, e + 1)
            else
                line = ""
            end
        end
        line = read("[^\n]*{\n}")
    end
    
    -- pass 2
    ks = sort(keys(xref))
    i = 1
    while ks[i] do
        write(format("%9s:", ks[i]))
        j = 1
        while xref[ks[i]][j] do
            write(format("%3d", xref[ks[i]][j]))
            j = j + 1
        end
        write("\n")
        i = i + 1
    end
    

[top]