update index.html documentation
[luagraph.git] / examples / tablegraph.lua
blobb7cef38874cf6f6e00ce0aac137e129722877b10
1 local m = require "graph"
3 local vbox, hbox = m.vbox, m.hbox
5 -- Get rid of ':' in table representation - only for invisible strings
6 local function tname(t)
7 local s = string.gsub(tostring(t), ": ", "")
8 return s
9 end
11 -- Create a port name
12 local function tport(s)
13 return "<"..tname(s)..">"
14 end
16 -- Return a closure that creates a node from a table
17 local function tnode(g, t, cache)
18 cache = cache or {}
19 local fields = {}
20 for k,v in pairs(t) do
21 if type(v) == "table" then
22 if t ~= v and v ~= _G and v~= _G.graph then
23 if cache[v] == nil then
24 cache[v] = k
25 table.insert(fields, vbox{tostring(k), tport(k)..tostring(v)})
26 tnode(g, v, cache)
27 end
28 g:edge(tname(t)..":"..tname(k), tname(v))
29 end
30 else
31 table.insert(fields, vbox{tostring(k), tport(k)..tostring(v)})
32 end
33 end
34 g:record{tname(t), hbox{tostring(t), unpack(fields)}}
35 end
37 -- Retrun a graph representing a nested table structure
38 local function tgraph(t)
39 local g = m.open("GG")
40 g.rankdir="LR"
41 tnode(g, t)
42 return g
43 end
45 ------------------------------------------
46 -- Example tables
47 ------------------------------------------
48 local xt = {
49 a=1,
50 b="some text",
51 c=3
54 local et = {}
55 et[1] = {
56 [1] = "index-1",
57 aField = "This is a field",
58 anotherField = "This is another field",
59 aTable = {
60 subfield = "subfield",
61 [1] = "index aTable[1]",
62 subtab = {
63 f = 3,
64 [1] = {
65 name="herbert",
66 age=47
69 anumber = 200
71 xf = "duda",
72 t1 = xt,
74 x=2,y=3
76 numField = 999,
79 local t = {}
80 for i = 1,3 do
81 t[i] = {}
82 for j = 1,4 do
83 t[i][j] = "field["..i.."]["..j.."]"
84 end
85 end
86 et[2] = t
88 local ende = false
89 while not ende do
90 print()
91 print("Select table to show:")
92 print("(1) example table")
93 print("(2) double indexed array")
94 print("(3) snmp module")
95 print("(4) socket module")
96 print("(5) binary tree")
97 print("(q) quit")
98 io.write("select: ") io.flush()
99 local s = io.read()
100 if s == "q" then
101 ende = true
102 else
103 if s == "3" then
104 et[3] = require "snmp"
106 if s == "4" then
107 et[4] = require "socket"
108 print(et[4])
110 if s == "5" then
111 local foo = assert(loadfile("tree.lua"))
112 et[5] = foo()
114 local ix = tonumber(s)
115 if et[ix] ~= nil then
116 local g = tgraph(et[tonumber(s)])
117 print("Close the display window completely to continue.")
118 g:show()
119 g:render("png", "out.png", "dot")
120 g:close()
121 else
122 print("Selected item is NIL - cannot produce graph")