pidigits

-- The Great Computer Language Shootout
-- http://shootout.alioth.debian.org/
--
-- contributed by Isaac Gouy

-- requires BigNum library
-- http://oss.digirati.com.br/luabignum/

require( "BigNum.lua" ) ;

-- Transformation

local T = {}

function T.bigzero() return BigNum.new(0) end
function T.bigone() return BigNum.new(1) end
function T.bigten() return BigNum.new(10) end

function T.new(q,r,s,t)
   return {
       q = BigNum.new(q)
      ,r = BigNum.new(r)
      ,s = BigNum.new(s)
      ,t = BigNum.new(t)
      ,k = 0
      }
end

function T.unity() return T.new(1,0,0,1) end
function T.zero() return T.new(0,0,0,0) end

function T.compose(a,b)
   local qq = T.bigzero()
   local qr = T.bigzero()
   local rt = T.bigzero()
   local qrrt = T.bigzero()
   local sq = T.bigzero()
   local ts = T.bigzero()
   local sqts = T.bigzero()
   local sr = T.bigzero()
   local tt = T.bigzero()
   local srtt = T.bigzero()

   BigNum.mul(a.q,b.q,qq)

   BigNum.mul(a.q,b.r,qr)
   BigNum.mul(a.r,b.t,rt)
   BigNum.add(qr,rt,qrrt)

   BigNum.mul(a.s,b.q,sq)
   BigNum.mul(a.t,b.s,ts)
   BigNum.add(sq,ts,sqts)

   BigNum.mul(a.s,b.r,sr)
   BigNum.mul(a.t,b.t,tt)
   BigNum.add(sr,tt,srtt)

   return T.new(qq, qrrt, sqts, srtt)
end

function T.extract(a,j)
   local bigj = BigNum.new(j)
   local qj = T.bigzero()
   local qjr = T.bigzero()
   local sj = T.bigzero()
   local sjt = T.bigzero()
   local n = T.bigzero()
   local sjt = T.bigzero()

   BigNum.mul(a.q,bigj,qj)
   BigNum.add(qj,a.r,qjr)

   BigNum.mul(a.s,bigj,sj)
   BigNum.add(sj,a.t,sjt)

   local d = T.bigzero()
   local r = T.bigzero()
   BigNum.div(qjr,sjt,d,r)

   return math.floor( tonumber( BigNum.mt.tostring(d) ))
end

function T.next(a)
   a.k = a.k + 1
   a.q = BigNum.new(a.k)
   a.r = BigNum.new(4*a.k + 2)
   a.s = T.bigzero()
   a.t = BigNum.new(2*a.k + 1)
   return a
end

-- Pi Digit Stream

local P = {}

function P.new()
   return {
       z = T.unity()
      ,x = T.zero()
      ,inverse = T.zero()
      }
end

function P.produce(a,j)
   local i = a.inverse
   i.q = T.bigten()
   i.r = BigNum.new(-10*j)
   i.s = T.bigzero()
   i.t = T.bigone()
   return T.compose(i,a.z)
end

function P.consume(a,b)
   return T.compose(a.z,b)
end

function P.digit(a)
   return T.extract(a.z,3)
end

function P.isSafe(a,j)
   return j == T.extract(a.z,4)
end

function P.next(a)
   local y
   y = P.digit(a)
   if P.isSafe(a,y) then
      a.z = P.produce(a,y)
      return y
   else
      a.z = P.consume(a,T.next(a.x))
      return P.next(a)
   end
end

-- Main

n = tonumber(arg and arg[1]) or 27
i = 0
length = 10
pidigit = P.new()

while n > 0 do
   if n < length then
      for _ = 1,n do io.write( P.next(pidigit) ) end
      for _ = n,length do io.write( ' ' ) end
      i = i + n
   else
      for _ = 1,length do io.write( P.next(pidigit) ) end
      i = i + length
   end
   io.write('\t:', i, '\n')
   n = n - length
end


partialsums

-- The Computer Language Shootout
-- http://shootout.alioth.debian.org/
-- contributed by Mike Pall

local n = tonumber(arg[1])
local function pr(fmt, x) io.write(string.format(fmt, x)) end

local a1, a2, a3, a4, a5, a6, a7, a8, a9, alt = 1, 0, 0, 0, 0, 0, 0, 0, 0, 1
local sqrt, sin, cos = math.sqrt, math.sin, math.cos
for k=1,n do
  local k2, sk, ck = k*k, sin(k), cos(k)
  local k3 = k2*k
  a1 = a1 + (2/3)^k
  a2 = a2 + 1/sqrt(k)
  a3 = a3 + 1/(k2+k)
  a4 = a4 + 1/(k3*sk*sk)
  a5 = a5 + 1/(k3*ck*ck)
  a6 = a6 + 1/k
  a7 = a7 + 1/k2
  a8 = a8 + alt/k
  a9 = a9 + alt/(k+k-1)
  alt = -alt
end
pr("%.9f\t(2/3)^k\n", a1)
pr("%.9f\tk^-0.5\n", a2)
pr("%.9f\t1/k(k+1)\n", a3)
pr("%.9f\tFlint Hills\n", a4)
pr("%.9f\tCookson Hills\n", a5)
pr("%.9f\tHarmonic\n", a6)
pr("%.9f\tRiemann Zeta\n", a7)
pr("%.9f\tAlternating Harmonic\n", a8)
pr("%.9f\tGregory\n", a9)


xd

-- hex dump
-- usage: lua xd.lua < file
local offset=0
while true do
 local s=io.read(16)
 if s==nil then return end
 io.write(string.format("%08X  ",offset))
 string.gsub(s,"(.)",
 io.write(string.rep(" ",3*(16-string.len(s))))
 io.write(" ",string.gsub(s,"%c","."),"\n")
 offset=offset+16
end


fib

-- fibonacci function with cache

-- very inefficient fibonacci function
function fib(n)
	N=N+1
	if n<2 then
		return n
	else
		return fib(n-1)+fib(n-2)
	end
end

-- a general-purpose value cache
function cache(f)
	local c={}
	return function (x)
		local y=c[x]
		if not y then
			y=f(x)
			c[x]=y
		end
		return y
	end
end

-- run and time it
function test(s,f)
	N=0
--	local c=os.clock()
	local v=f(n)
--	local t=os.clock()-c
	local t=0
	print(s,n,v,t,N)
end

n=24		-- for other values, do lua fib.lua XX
n=tonumber(n)
print("","n","value","time","evals")
test("plain",fib)
fib=cache(fib)
test("cached",fib)


cf

-- temperature conversion table (celsius to farenheit)

for c0=-20,50-1,10 do
	io.write("C ")
	for c=c0,c0+10-1 do
		io.write(string.format("%3.0f ",c))
	end
	io.write("\n")

	io.write("F ")
	for c=c0,c0+10-1 do
		f=(9/5)*c+32
		io.write(string.format("%3.0f ",f))
	end
	io.write("\n\n")
end


trace-calls

-- trace calls
-- example: lua -ltrace-calls bisect.lua
local level=0
local function hook(event)
 local t=debug.getinfo(3)
 io.write(level," >>> ",string.rep(" ",level))
 if t~=nil and t.currentline>=0 then io.write(t.short_src,":",t.currentline," ") end
 t=debug.getinfo(2)
 if event=="call" then
  level=level+1
 else
  level=level-1 if level<0 then level=0 end
 end
 if t.what=="main" then
  if event=="call" then
   io.write("begin ",t.short_src)
  else
   io.write("end ",t.short_src)
  end
 elseif t.what=="Lua" then
-- table.foreach(t,print)
  io.write(event," ",t.name or "(Lua)"," <",t.linedefined,":",t.short_src,">")
 else
 end
 io.write("\n")
end
debug.sethook(hook,"cr")
level=0


table

-- make table, grouping all data for the same item
-- input is 2 columns (item, data)

local A
while 1 do
 local l=io.read()
 if l==nil then break end
 local _,_,a,b=string.find(l,'"?([_%w]+)"?%s*(.*)$')
 if a~=A then A=a io.write("\n",a,":") end
 io.write(" ",b)
end
io.write("\n")


printf

-- an implementation of printf

function printf(...)
 io.write(string.format(...))
end

printf("Hello %s from %s on %s\n",os.getenv"USER" or "there",_VERSION,os.date())


sieve

-- the sieve of of Eratosthenes programmed with coroutines
-- typical usage: lua -e N=1000 sieve.lua | column

-- generate all the numbers from 2 to n
function gen (n)
  return coroutine.wrap(function ()
    for i=2,n do coroutine.yield(i) end
  end)
end

-- filter the numbers generated by `g', removing multiples of `p'
function filter (p, g)
  return coroutine.wrap(function ()
    while 1 do
      local n = g()
      if n == nil then return end
      if math.mod(n, p) ~= 0 then coroutine.yield(n) end
    end
  end)
end

N=N or 1000		-- from command line
x = gen(N)		-- generate primes up to N
while 1 do
  local n = x()		-- pick a number until done
  if n == nil then break end
  print(n)		-- must be a prime number
  x = filter(n, x)	-- now remove its multiples
end


luac

-- bare-bones luac in Lua
-- usage: lua luac.lua file.lua

assert(arg[1]~=nil and arg[2]==nil,"usage: lua luac.lua file.lua")
f=assert(io.open("luac.out","wb"))
assert(f:write(string.dump(assert(loadfile(arg[1])))))
assert(f:close())


sort

-- two implementations of a sort function
-- this is an example only. Lua has now a built-in function "sort"

-- extracted from Programming Pearls, page 110
function qsort(x,l,u,f)
 if l<u then
  local m=math.random(u-(l-1))+l-1	-- choose a random pivot in range l..u
  x[l],x[m]=x[m],x[l]			-- swap pivot to first position
  local t=x[l]				-- pivot value
  m=l
  local i=l+1
  while i<=u do
    -- invariant: x[l+1..m] < t <= x[m+1..i-1]
    if f(x[i],t) then
      m=m+1
      x[m],x[i]=x[i],x[m]		-- swap x[i] and x[m]
    end
    i=i+1
  end
  x[l],x[m]=x[m],x[l]			-- swap pivot to a valid place
  -- x[l+1..m-1] < x[m] <= x[m+1..u]
  qsort(x,l,m-1,f)
  qsort(x,m+1,u,f)
 end
end

function selectionsort(x,n,f)
 local i=1
 while i<=n do
  local m,j=i,i+1
  while j<=n do
   if f(x[j],x[m]) then m=j end
   j=j+1
  end
 x[i],x[m]=x[m],x[i]			-- swap x[i] and x[m]
 i=i+1
 end
end

function show(m,x)
 io.write(m,"\n\t")
 local i=1
 while x[i] do
  io.write(x[i])
  i=i+1
  if x[i] then io.write(",") end
 end
 io.write("\n")
end

function testsorts(x)
 local n=1
 while x[n] do n=n+1 end; n=n-1		-- count elements
 show("original",x)
 qsort(x,1,n,function (x,y) return x<y end)
 show("after quicksort",x)
 selectionsort(x,n,function (x,y) return x>y end)
 show("after reverse selection sort",x)
 qsort(x,1,n,function (x,y) return x<y end)
 show("after quicksort again",x)
end

-- array to be sorted
x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}

testsorts(x)


bisect

-- bisection method for solving non-linear equations
delta=1e-6	-- tolerance
function bisect(f,a,b,fa,fb)
 local c=(a+b)/2
 io.write(n," c=",c," a=",a," b=",b,"\n")
 if c==a or c==b or math.abs(a-b)<delta then return c,b-a end
 n=n+1
 if fa*fc<0 then return bisect(f,a,c,fa,fc) else return bisect(f,c,b,fc,fb) end
end
-- find root of f in the inverval [a,b]. needs f(a)*f(b)<0
function solve(f,a,b)
 n=0
 local z,e=bisect(f,a,b,f(a),f(b))
 io.write(string.format("after %d steps, root is %.17g with error %.1e, f=%.1e\n",n,z,e,f(z)))
end
-- our function
function f(x)
 return x*x*x-x-1
end
-- find zero in [1,2]
solve(f,1,2)


echo

-- echo command line arguments

for i=0,table.getn(arg) do
 print(i,arg[i])
end


env

-- read environment variables as if they were global variables

local f=function (t,i) return os.getenv(i) end
setmetatable(getfenv(),{__index=f})

-- an example
print(a,USER,PATH)


hello

-- the first program in every language

io.write("Hello world, from ",_VERSION,"!\n")


fibfor

-- example of for with generator functions

function generatefib (n)
  return coroutine.wrap(function ()
    local a,b = 1, 1
    while a <= n do
      coroutine.yield(a)
      a, b = b, a+b
    end
  end)
end

for i in generatefib(1000) do print(i) end


trace-globals

-- trace assigments to global variables

do
 -- a tostring that quotes strings. note the use of the original tostring.
 local _tostring=tostring
 local tostring=function(a)
  if type(a)=="string" then
   return string.format("%q",a)
  else
   return _tostring(a)
  end
 end

 local log=function (name,old,new)
  local t=debug.getinfo(3,"Sl")
  local line=t.currentline
  io.write(t.short_src)
  if line>=0 then io.write(":",line) end
  io.write(": ",name," is now ",tostring(new)," (was ",tostring(old),")","\n")
 end

 local g={}
 local set=function (t,name,value)
  log(name,g[name],value)
  g[name]=value
 end
 setmetatable(getfenv(),{__index=g,__newindex=set})
end

-- an example

a=1
b=2
a=10
b=20
b=nil
b=200
print(a,b,c)


factorial

-- function closures are powerful

-- traditional fixed-point operator from functional programming
Y = function (g)
      local a = function (f) return f(f) end
      return a(function (f)
                 return g(function (x)
                             local c=f(f)
                             return c(x)
                           end)
               end)
end

-- factorial without recursion
F = function (f)
      return function (n)
               if n == 0 then return 1
               else return n*f(n-1) end
             end
    end

factorial = Y(F)   -- factorial is the fixed point of F

-- now test it
function test(x)
	io.write(x,"! = ",factorial(x),"\n")
end

for n=0,16 do
	test(n)
end


globals

-- reads luac listings and reports global variable usage
-- lines where a global is written to are marked with "*"
-- typical usage: luac -p -l file.lua | lua globals.lua | sort | lua table.lua

while 1 do
 local s=io.read()
 if s==nil then break end
 local ok,_,l,op,g=string.find(s,"%[%-?(%d*)%]%s*([GS])ETGLOBAL.-;%s+(.*)$")
 if ok then
  if op=="S" then op="*" else op="" end
  io.write(g,"\t",l,op,"\n")
 end
end


function sk_scrape_startcanvas(c, fileName) end

function sk_scrape_endcanvas(c, fileName) end

function classify_rrect(rrect)
    if (rrect:type() == "simple") then
        local x, y = rrect:radii(0)
        if (x == y) then
            return "simple_circle"
        else
            return "simple_oval"
        end
    elseif (rrect:type() == "complex") then
        local numNotSquare = 0
        local rx, ry
        local same = true;
        local first_not_square_corner
        local last_not_square_corner
        for i = 1, 4 do
            local x, y = rrect:radii(i-1)
            if (x ~= 0 and y ~= 0) then
                if (numNotSquare == 0) then
                    rx = x
                    ry = y
                    first_not_square_corner = i
                else
                   last_not_square_corner = i
                   if (rx ~= x or ry ~=y) then
                       same = false
                   end
                end
                numNotSquare = numNotSquare + 1
            end
        end
        local numSquare = 4 - numNotSquare
        if (numSquare > 0 and same) then
            local corners = "corners"
            if (numSquare == 2) then
                if ((last_not_square_corner - 1 == first_not_square_corner) or
                    (1 == first_not_square_corner and 4 == last_not_square_corner )) then
                    corners = "adjacent_" .. corners
                else
                    corners = "opposite_" .. corners
                end
            elseif (1 == numSquare) then
                corners = "corner"
            end
            if (rx == ry) then
                return "circles_with_" .. numSquare .. "_square_" .. corners
            else
                return "ovals_with_" .. numSquare .. "_square_" .. corners
            end
        end
        return "complex_unclassified"
    elseif (rrect:type() == "rect") then
        return "rect"
    elseif (rrect:type() == "oval") then
        local x, y = rrect:radii(0)
        if (x == y) then
            return "circle"
        else
            return "oval"
        end
    elseif (rrect:type() == "empty") then
        return "empty"
    else
        return "unknown"
    end
end

function print_classes(class_table)
  function sort_classes(a, b)
     return a.count > b.count
  end
  array = {}
  for k, v in pairs(class_table) do
      if (type(v) == "number") then
          array[#array + 1] = {class = k, count = v};
      end
  end
  table.sort(array, sort_classes)
  local i
  for i = 1, #array do
      io.write(array[i].class, ": ", array[i].count, " (", array[i].count/class_table["total"] * 100, "%)\n");
  end
end

function sk_scrape_accumulate(t)
    if (t.verb == "clipRRect") then
        local rrect = t.rrect
        table["total"] = (table["total"] or 0) + 1
        local class = classify_rrect(rrect)
        table[class] = (table[class] or 0) + 1
    end
end

function sk_scrape_summarize()
  print_classes(table)
  --[[ To use the web scraper comment out the above call to print_classes, run the code below,
       and in the aggregator pass agg_table to print_classes.
  for k, v in pairs(table) do
      if (type(v) == "number") then
          local t = "agg_table[\"" .. k .. "\"]"
          io.write(t, " = (", t, " or 0) + ", table[k], "\n" );
      end
  end
  --]]
end


local canvas        -- holds the current canvas (from startcanvas())

--[[
    startcanvas() is called at the start of each picture file, passing the
    canvas that we will be drawing into, and the name of the file.

    Following this call, there will be some number of calls to accumulate(t)
    where t is a table of parameters that were passed to that draw-op.

        t.verb is a string holding the name of the draw-op (e.g. "drawRect")

    when a given picture is done, we call endcanvas(canvas, fileName)
]]
function sk_scrape_startcanvas(c, fileName)
    canvas = c
end

--[[
    Called when the current canvas is done drawing.
]]
function sk_scrape_endcanvas(c, fileName)
    canvas = nil
end

--[[
    Use to initialize all keys passed in keyTable to zero in table.
    Useful so that keys that are never get incremented still output zero at end
]]
function resetTableKeys(table, keyTable)
    for k, v in next, keyTable do
        table[v] = 0
    end
end

function increment(table, key)
    table[key] = (table[key] or 0) + 1
end

local dashCount = 0

local total_found = {}
local drawPoints_count = {}
local drawPoints_direction = {}
resetTableKeys(drawPoints_direction, {"hori", "vert", "other"})
local dashInterval_count = {}
local dashInterval_pattern = {}
resetTableKeys(dashInterval_pattern, {"one_one", "zero_on", "other"})
local dash_phase = {}
resetTableKeys(dash_phase, {"zero", "other"})
local dash_cap = {}
resetTableKeys(dash_cap, {"butt", "round", "square"})

local dashTable = {}
dashTable.total_found = total_found
dashTable.drawPoints_count = drawPoints_count
dashTable.drawPoints_direction = drawPoints_direction
dashTable.dashInterval_count = dashInterval_count
dashTable.dashInterval_pattern = dashInterval_pattern
dashTable.dash_phase = dash_phase
dashTable.dash_cap = dash_cap

function sk_scrape_accumulate(t)
    local p = t.paint
    if p then
        local pe = p:getPathEffect()
        if pe then
            local de = pe:asADash()
            if de then
                dashCount = dashCount + 1
                increment(total_found, t.verb);
                increment(dashInterval_count, #de.intervals)
                if 2 == #de.intervals then
		    if 1 == de.intervals[1] and 1 == de.intervals[2] then
                        increment(dashInterval_pattern, "one_one")
                    elseif 0 == de.intervals[1] then
                        increment(dashInterval_pattern, "zero_on")
                    else
                        increment(dashInterval_pattern, "other")
                    end
                end

                if 0 == de.phase then
                    increment(dash_phase, "zero")
                else
                    increment(dash_phase, "other")
                end

                local cap = p:getStrokeCap()
                if 0 == cap then
                    increment(dash_cap, "butt")
                elseif 1 == cap then
                    increment(dash_cap, "round")
                else
                    increment(dash_cap, "square")
                end

                if "drawPoints" == t.verb then
                    local points = t.points
                    increment(drawPoints_count, #points)
                    if 2 == #points then
                        if points[1].y == points[2].y then
                            increment(drawPoints_direction, "hori")
                        elseif points[1].x == points[2].x then
                            increment(drawPoints_direction, "vert")
                        else
                            increment(drawPoints_direction, "other")
                        end
                    end
                end

                --[[
                    eventually would like to print out info on drawPath verbs with dashed effect
                ]]
                if "drawPath" == t.verb then
                end

            end
        end
    end
end

--[[
    lua_pictures will call this function after all of the pictures have been
    "accumulated".
]]
function sk_scrape_summarize()
-- use for non telemetry
--[[
    io.write("Total dashed effects is: ", dashCount, "\n");
    for k1, v1 in next, dashTable do
        io.write("\nTable: ", k1, "\n")
        for k, v in next, v1 do
            io.write("\"", k, "\": ", v, "\n")
        end
    end
]]

-- use for telemetry
    io.write("\ndashCount = dashCount + ", tostring(dashCount), "\n")
    for k1, v1 in next, dashTable do
        for k, v in next, v1 do
            io.write("\nincrement(dashTable, \"", k1, "\", \"", k, "\", ", v, ")\n")
        end
    end
end


gradients

function sk_scrape_startcanvas(c, fileName) end

function sk_scrape_endcanvas(c, fileName) end

count3 = 0
count3sym = 0

function sk_scrape_accumulate(t)
    local p = t.paint
    if p then
        local s = p:getShader()
        if s then
            local g = s:asAGradient()
            if g then
                --io.write(g.type, " gradient with ", g.colorCount, " colors\n")

                if g.colorCount == 3 then
                   count3 = count3 + 1

                   if (g.midPos >= 0.499 and g.midPos <= 0.501) then
                      count3sym = count3sym + 1
                   end
                end
            end
        end
    end
end

function sk_scrape_summarize()
         io.write("Number of 3 color gradients:  ", count3, "\n");
         io.write("Number of 3 color symmetric gradients:  ", count3sym, "\n");
end


chars-vs-glyphs

local canvas

function sk_scrape_startcanvas(c, fileName)
    canvas = c
end

function sk_scrape_endcanvas(c, fileName)
    canvas = nil
end

local glyph_calls = 0
local unichar_calls = 0

local isTextVerbs = {
    drawPosText = true,
    drawPosTextH = true,
    drawText = true,
    drawTextOnPath = true,
}

function sk_scrape_accumulate(t)
    if isTextVerbs[t.verb] then
        if t.glyphs then
            glyph_calls = glyph_calls + 1
        else
            unichar_calls = unichar_calls + 1
        end
    end
end

function sk_scrape_summarize()
    io.write("glyph calls = ", glyph_calls,
             ", unichar calls = ", unichar_calls, "\n");
end


skia

-- Experimental helpers for skia --

function string.startsWith(String,Start)
   return string.sub(String,1,string.len(Start))==Start
end

function string.endsWith(String,End)
   return End=='' or string.sub(String,-string.len(End))==End
end

Sk = {}

function Sk.isFinite(x)
    return x * 0 == 0
end

-------------------------------------------------------------------------------

Sk.Rect = { left = 0, top = 0, right = 0, bottom = 0 }
Sk.Rect.__index = Sk.Rect

function Sk.Rect.new(l, t, r, b)
    local rect
    if r then
        -- 4 arguments
        rect = { left = l, top = t, right = r, bottom = b }
    elseif l then
        -- 2 arguments
        rect = { right = l, bottom = t }
    else
        -- 0 arguments
        rect = {}
    end
    setmetatable(rect, Sk.Rect)
    return rect;
end

function Sk.Rect:width()
    return self.right - self.left
end

function Sk.Rect:height()
    return self.bottom - self.top
end

function Sk.Rect:isEmpty()
    return self:width() <= 0 or self:height() <= 0
end

function Sk.Rect:isFinite()
    local value = self.left * 0
    value = value * self.top
    value = value * self.right
    value = value * self.bottom
    return 0 == value
end

function Sk.Rect:setEmpty()
    self.left = 0
    self.top = 0
    self.right = 0
    self.bottom = 0
end

function Sk.Rect:set(l, t, r, b)
    self.left = l
    self.top = t
    self.right = r
    self.bottom = b
end

function Sk.Rect:offset(dx, dy)
    dy = dy or dx

    self.left = self.left + dx
    self.top = self.top + dy
    self.right = self.right + dx
    self.bottom = self.bottom + dy
end

function Sk.Rect:inset(dx, dy)
    dy = dy or dx

    self.left = self.left + dx
    self.top = self.top + dy
    self.right = self.right - dx
    self.bottom = self.bottom - dy
end

-------------------------------------------------------------------------------


function sk_scrape_startcanvas(c, fileName)
    canvas = c
    clipstack = {}
    restoreCount = 0
end

function sk_scrape_endcanvas(c, fileName)
    canvas = nil
end

function sk_scrape_accumulate(t)
    if (t.verb == "restore") then
        restoreCount = restoreCount + 1;
        -- io.write("Clip Stack at restore #", restoreCount, ":\n")
        io.write("Reduced Clip Stack at restore #", restoreCount, ":\n")
        for i = 1, #clipstack do
            local element = clipstack[i];
            io.write("\t", element["op"], ", ", element["type"], ", aa:", tostring(element["aa"]))
            if (element["type"] == "path") then
                io.write(", fill: ", element["path"]:getFillType())
                io.write(", segments: \"", element["path"]:getSegmentTypes(), "\"")
                io.write(", convex:", tostring(element["path"]:isConvex()))
            end
            io.write("\n")
        end
        io.write("\n")
    else
        -- clipstack = canvas:getClipStack()
        clipstack = canvas:getReducedClipStack()
    end
end

function sk_scrape_summarize() end


function tostr(t)
    local str = ""
    for k, v in next, t do
        if #str > 0 then
            str = str .. ", "
        end
        if type(k) == "number" then
            str = str .. "[" .. k .. "] = "
        else
            str = str .. tostring(k) .. " = "
        end
        if type(v) == "table" then
            str = str .. "{ " .. tostr(v) .. " }"
        else
            str = str .. tostring(v)
        end
    end
    return str
end

function sk_scrape_startcanvas(c, fileName) end

function sk_scrape_endcanvas(c, fileName) end

local effects = {}

function count_fields(t)
    for k, v in next, t do
        effects[k] = (effects[k] or 0) + 1
    end
end

local total_paints = 0;

function sk_scrape_accumulate(t)
    if (t.paint) then
        total_paints = total_paints + 1
        count_fields(t.paint:getEffects())
    end
end

function sk_scrape_summarize()
    io.write("total paints ", total_paints, " ", tostr(effects), "\n");
end


-- bbh_filter.lua
--
-- This script outputs info about 'interesting' skp files,
-- where the definition of 'interesting' changes but is roughly:
-- "Interesting for bounding box hierarchy benchmarks."
--
-- Currently, the approach is to output, in equal ammounts, the names of the files that
-- have most commands, and the names of the files that use the least popular commands.

function count_entries(table)
    local count = 0
    for _,_ in pairs(table) do
        count = count + 1
    end
    return count
end

verbCounts = {}

function reset_current()
    -- Data about the skp in transit
    currentInfo = {
        fileName = '',
        verbs = {},
        numOps = 0
    }
end
reset_current()

numOutputFiles = 10  -- This is per measure.
globalInfo = {}  -- Saves currentInfo for each file to be used at the end.
output = {}  -- Stores {fileName, {verb, count}} tables.

function tostr(t)
    local str = ""
    for k, v in next, t do
        if #str > 0 then
            str = str .. ", "
        end
        if type(k) == "number" then
            str = str .. "[" .. k .. "] = "
        else
            str = str .. tostring(k) .. " = "
        end
        if type(v) == "table" then
            str = str .. "{ " .. tostr(v) .. " }"
        else
            str = str .. tostring(v)
        end
    end
    return str
end

function sk_scrape_startcanvas(c, fileName) end

function sk_scrape_endcanvas(c, fileName)
    globalInfo[fileName] = currentInfo
    globalInfo[fileName].fileName = fileName
    reset_current()
end

function sk_scrape_accumulate(t)
    -- dump the params in t, specifically showing the verb first, which we
    -- then nil out so it doesn't appear in tostr()
    --
    verbCounts[t.verb] = (verbCounts[t.verb] or 0) + 1
    currentInfo.verbs[t.verb] = (currentInfo.verbs[t.verb] or 0) + 1
    currentInfo.numOps = currentInfo.numOps + 1

    t.verb = nil
end

function sk_scrape_summarize()
    verbWeights = {}  -- {verb, weight}, where 0 < weight <= 1

    meta = {}
    for k,v in pairs(verbCounts) do
        table.insert(meta, {key=k, value=v})
    end
    table.sort(meta, function (a,b) return a.value > b.value; end)
    maxValue = meta[1].value
    io.write("-- ==================\n")
    io.write("------------------------------------------------------------------ \n")
    io.write("-- Command\t\t\tNumber of calls\t\tPopularity\n")
    io.write("------------------------------------------------------------------ \n")
    for k, v in pairs(meta) do
        verbWeights[v.key] = v.value / maxValue

        -- Poor man's formatting:
        local padding = "\t\t\t"
        if (#v.key + 3) < 8 then
            padding = "\t\t\t\t"
        end
        if (#v.key + 3) >= 16 then
            padding = "\t\t"
        end

        io.write ("-- ",v.key, padding, v.value, '\t\t\t', verbWeights[v.key], "\n")
    end

    meta = {}
    function calculate_weight(verbs)
        local weight = 0
        for name, count in pairs(verbs) do
            weight = weight + (1 / verbWeights[name]) * count
        end
        return weight
    end
    for n, info in pairs(globalInfo) do
        table.insert(meta, info)
    end

    local visitedFiles = {}

    -- Prints out information in lua readable format
    function output_with_metric(metric_func, description, numOutputFiles)
        table.sort(meta, metric_func)
        print(description)
        local iter = 0
        for i, t in pairs(meta) do
            if not visitedFiles[t.fileName] then
                visitedFiles[t.fileName] = true
                io.write ("{\nname = \"", t.fileName, "\", \nverbs = {\n")
                for verb,count in pairs(globalInfo[t.fileName].verbs) do
                    io.write('    ', verb, " = ", count, ",\n")
                end
                io.write("}\n},\n")

                iter = iter + 1
                if iter >= numOutputFiles then
                    break
                end
            end
        end
    end

    output_with_metric(
        function(a, b) return calculate_weight(a.verbs) > calculate_weight(b.verbs); end,
        "\n-- ================== skps with calling unpopular commands.", 10)
    output_with_metric(
        function(a, b) return a.numOps > b.numOps; end,
        "\n-- ================== skps with the most calls.", 50)

    local count = count_entries(visitedFiles)

    print ("-- Spat", count, "files")
end


function tostr(t)
    local str = ""
    for k, v in next, t do
        if #str > 0 then
            str = str .. ", "
        end
        if type(k) == "number" then
            str = str .. "[" .. k .. "] = "
        else
            str = str .. tostring(k) .. " = "
        end
        if type(v) == "table" then
            str = str .. "{ " .. tostr(v) .. " }"
        else
            str = str .. tostring(v)
        end
    end
    return str
end

local total_found = {}    -- accumulate() stores its data in here
local total_total = {}
local canvas        -- holds the current canvas (from startcanvas())

--[[
    startcanvas() is called at the start of each picture file, passing the
    canvas that we will be drawing into, and the name of the file.

    Following this call, there will be some number of calls to accumulate(t)
    where t is a table of parameters that were passed to that draw-op.

        t.verb is a string holding the name of the draw-op (e.g. "drawRect")

    when a given picture is done, we call endcanvas(canvas, fileName)
]]
function sk_scrape_startcanvas(c, fileName)
    canvas = c
end

--[[
    Called when the current canvas is done drawing.
]]
function sk_scrape_endcanvas(c, fileName)
    canvas = nil
end

function increment(table, key)
    table[key] = (table[key] or 0) + 1
end

local drawPointsTable = {}
local drawPointsTable_direction = {}

function sk_scrape_accumulate(t)
    increment(total_total, t.verb)

    local p = t.paint
    if p then
        local pe = p:getPathEffect();
        if pe then
            increment(total_found, t.verb)
        end
    end

    if "drawPoints" == t.verb then
        local points = t.points
        increment(drawPointsTable, #points)
        if 2 == #points then
            if points[1].y == points[2].y then
                increment(drawPointsTable_direction, "hori")
            elseif points[1].x == points[2].x then
                increment(drawPointsTable_direction, "vert")
            else
                increment(drawPointsTable_direction, "other")
            end
        end
    end
end

--[[
    lua_pictures will call this function after all of the pictures have been
    "accumulated".
]]
function sk_scrape_summarize()
    for k, v in next, total_found do
        io.write(k, " = ", v, "/", total_total[k], "\n")
    end
    print("histogram of point-counts for all drawPoints calls")
    print(tostr(drawPointsTable))
    print(tostr(drawPointsTable_direction))
end


stats = {}

-- switch this to run on the automated scraper system
newline = "\n"
-- newline = "\\n"

function sk_scrape_startcanvas(c, fileName)
    canvas = c
    oldstackstr = "<invalid>"
end

function sk_scrape_endcanvas(c, fileName)
    canvas = nil
end

function string.starts(String,Start)
   return string.sub(String,1,string.len(Start))==Start
end

function build_stack_string(stack)
    local info = ""
    for i = 1, #stack do
        local element = stack[i];
        info = info .. element["op"] .. ", " .. element["type"] .. ", aa:" .. tostring(element["aa"])
        if (element["type"] == "path") then
            if (element["path"]:getSegmentTypes() == "line" and element["path"]:isConvex()) then
                info = info .. ", convex_poly " .. element["path"]:countPoints() .. " points"
            else
                info = info .. ", fill: " .. element["path"]:getFillType()
                info = info .. ", segments: (" .. element["path"]:getSegmentTypes() .. ")"
                info = info .. ", convex:" .. tostring(element["path"]:isConvex())
            end
        end
        info = info .. newline
    end
    return info
end

function sk_scrape_accumulate(t)
    if (string.starts(t.verb, "draw")) then
        local stack = canvas:getReducedClipStack()
        local stackstr = build_stack_string(stack)
        if (stackstr ~= "") then
            if (stats[stackstr] == nil) then
                stats[stackstr] = {}
                stats[stackstr].drawCnt = 0
                stats[stackstr].instanceCnt = 0
            end
            stats[stackstr].drawCnt = stats[stackstr].drawCnt + 1
            if (stackstr ~= oldstackstr) then
                stats[stackstr].instanceCnt = stats[stackstr].instanceCnt + 1
            end
        end
        oldstackstr = stackstr
    end
end

function print_stats(stats)
    function sort_by_draw_cnt(a, b)
        return a.data.drawCnt > b.data.drawCnt
    end
    array = {}
    for k,v in pairs(stats) do
        array[#array + 1] = { name = k, data = v }
    end
    table.sort(array, sort_by_draw_cnt)
    for i = 1, #array do
        io.write("\n-------\n", array[i].name, tostring(array[i].data.drawCnt), " draws, ", tostring(array[i].data.instanceCnt), " instances.\n")
    end
end

function sk_scrape_summarize()
    print_stats(stats)
    --[[ To use the web scraper comment out the print above, run the code below to generate an
         aggregate table on the automated scraper system. Then use the print_stats function on
         agg_stats in the aggregator step.
    for k,v in pairs(stats) do
        if (v.drawCnt ~= nil) then
             -- io.write("\n-------\n", k, tostring(v.drawCnt), " draws, ", tostring(v.instanceCnt), " instances.\n")
             local tableEntry = 'agg_stats["' .. k .. '"]'
             io.write(tableEntry, " = ", tableEntry, " or {}\n")
             io.write(tableEntry, ".drawCnt = (", tableEntry, ".drawCnt or 0 ) + ", v.drawCnt, "\n")
             io.write(tableEntry, ".instanceCnt = (", tableEntry, ".instanceCnt or 0 ) + ", v.instanceCnt, "\n")
        end
    end
    --]]
end


--[[
    This file is used as the aggregator file when using telemetry for
    scrape_dashing_full.lua
]]

dashCount = 0
dashTable = {}

function increment_inner(table, key, value)
    table[key] = (table[key] or 0) + value
end

function increment(table, tableKey, key, value)
    if (table[tableKey] == nil) then
        table[tableKey] = {}
    end
    increment_inner(table[tableKey], key, value)
end

dofile("/tmp/lua-output")

io.write("Total dashed effects is: ", dashCount, "\n")
for k1, v1 in next, dashTable do
    io.write("\nTable: ", k1, "\n")
    for k, v in next, v1 do
        io.write("\"", k, "\": ", v, "\n")
    end
end


function string.startsWith(String,Start)
   return string.sub(String,1,string.len(Start))==Start
end

function string.endsWith(String,End)
   return End=='' or string.sub(String,-string.len(End))==End
end

local canvas = nil
local num_perspective_bitmaps = 0
local num_affine_bitmaps = 0
local num_scaled_bitmaps = 0
local num_translated_bitmaps = 0
local num_identity_bitmaps = 0
local num_scaled_up = 0
local num_scaled_down = 0

function sk_scrape_startcanvas(c, fileName)
  canvas = c
end

function sk_scrape_endcanvas(c, fileName)
  canvas = nil
end

function sk_scrape_accumulate(t)
    -- dump the params in t, specifically showing the verb first, which we
    -- then nil out so it doesn't appear in tostr()
    if (string.startsWith(t.verb,"drawBitmap")) then
      matrix = canvas:getTotalMatrix()
      matrixType = matrix:getType()
      if matrixType.perspective then
        num_perspective_bitmaps = num_perspective_bitmaps + 1
      elseif matrixType.affine then
        num_affine_bitmaps = num_affine_bitmaps + 1
      elseif matrixType.scale then
        num_scaled_bitmaps = num_scaled_bitmaps + 1
        if matrix:getScaleX() > 1 or matrix:getScaleY() > 1 then
          num_scaled_up = num_scaled_up + 1
        else
          num_scaled_down = num_scaled_down + 1
        end
      elseif matrixType.translate then
        num_translated_bitmaps = num_translated_bitmaps + 1
      else
        num_identity_bitmaps = num_identity_bitmaps + 1
      end
    end
end

function sk_scrape_summarize()
  io.write( "identity = ", num_identity_bitmaps,
            ", translated = ", num_translated_bitmaps,
            ", scaled = ", num_scaled_bitmaps, " (up = ", num_scaled_up, "; down = ", num_scaled_down, ")",
            ", affine = ", num_affine_bitmaps,
            ", perspective = ", num_perspective_bitmaps,
            "\n")
end


scrape

function tostr(t)
    local str = ""
    for k, v in next, t do
        if #str > 0 then
            str = str .. ", "
        end
        if type(k) == "number" then
            str = str .. "[" .. k .. "] = "
        else
            str = str .. tostring(k) .. " = "
        end
        if type(v) == "table" then
            str = str .. "{ " .. tostr(v) .. " }"
        else
            str = str .. tostring(v)
        end
    end
    return str
end
local total = {}    -- accumulate() stores its data in here
local canvas        -- holds the current canvas (from startcanvas())
--[[
    startcanvas() is called at the start of each picture file, passing the
    canvas that we will be drawing into, and the name of the file.

    Following this call, there will be some number of calls to accumulate(t)
    where t is a table of parameters that were passed to that draw-op.

        t.verb is a string holding the name of the draw-op (e.g. "drawRect")

    when a given picture is done, we call endcanvas(canvas, fileName)
]]
function sk_scrape_startcanvas(c, fileName)
    canvas = c
end
--[[
    Called when the current canvas is done drawing.
]]
function sk_scrape_endcanvas(c, fileName)
    canvas = nil
end
--[[
    Called with the parameters to each canvas.draw call, where canvas is the
    current canvas as set by startcanvas()
]]
function sk_scrape_accumulate(t)
    local n = total[t.verb] or 0
    total[t.verb] = n + 1
    if false and t.verb == "drawRect" and t.paint:isAntiAlias() then
        local r = t.rect;
        local p = t.paint;
        local c = p:getColor();
    end
    if false and t.verb == "drawPath" then
        local pred, r1, r2, d1, d2 = t.path:isNestedRects()

        if pred then
            print("drawRect_Nested", tostr(r1), tostr(r2), d1, d2)
        else
            print("drawPath", "isEmpty", tostring(t.path:isEmpty()),
                    "isRect", tostring(t.path:isRect()), tostr(t.path:getBounds()))
        end
    end
end
--[[
    lua_pictures will call this function after all of the pictures have been
    "accumulated".
]]
function sk_scrape_summarize()
    io.write("\n{ ", tostr(total), " }\n")
end


glyph-usage

function tostr(t)
    local str = ""
    for k, v in next, t do
        if #str > 0 then
            str = str .. ", "
        end
        if type(k) == "number" then
            str = str .. "[" .. k .. "] = "
        else
            str = str .. tostring(k) .. " = "
        end
        if type(v) == "table" then
            str = str .. "{ " .. tostr(v) .. " }"
        else
            str = str .. tostring(v)
        end
    end
    return str
end

local canvas        -- holds the current canvas (from startcanvas())

--[[
    startcanvas() is called at the start of each picture file, passing the
    canvas that we will be drawing into, and the name of the file.

    Following this call, there will be some number of calls to accumulate(t)
    where t is a table of parameters that were passed to that draw-op.

        t.verb is a string holding the name of the draw-op (e.g. "drawRect")

    when a given picture is done, we call endcanvas(canvas, fileName)
]]
function sk_scrape_startcanvas(c, fileName)
    canvas = c
end

--[[
    Called when the current canvas is done drawing.
]]
function sk_scrape_endcanvas(c, fileName)
    canvas = nil
end

--[[
    Called with the parameters to each canvas.draw call, where canvas is the
    current canvas as set by startcanvas()
]]

function round(x, mul)
    mul = mul or 1
    return math.floor(x * mul + 0.5) / mul
end

dump_glyph_array_p = false

function dump_array_as_C(array)
    for k, v in next, array do
        io.write(tostring(v), ", ");
    end
    io.write("-1,\n")
end

local strikes = {}  -- [fontID_pointsize] = [] unique glyphs

function make_strike_key(paint)
    return paint:getFontID() * 1000 + paint:getTextSize()
end

-- array is an array of bools (true), using glyphID as the index
-- other is just an array[1...N] of numbers (glyphIDs)
function array_union(array, other)
    for k, v in next, other do
        array[v] = true;
    end
end

-- take a table of bools, indexed by values, and return a sorted table of values
function bools_to_values(t)
    local array = {}
    for k, v in next, t do
        array[#array + 1] = k
    end
    table.sort(array)
    return array
end

function array_count(array)
    local n = 0
    for k in next, array do
        n = n + 1
    end
    return n
end

function sk_scrape_accumulate(t)
    verb = t.verb;
    if verb == "drawPosText" or verb == "drawPosTextH" then
        if t.glyphs then
            local key = make_strike_key(t.paint)
            strikes[key] = strikes[key] or {}
            array_union(strikes[key], t.glyphs)

            if dump_glyph_array_p then
                dump_array_as_C(t.glyphs)
            end
        end
    end
end

--[[
    lua_pictures will call this function after all of the pictures have been
    "accumulated".
]]
function sk_scrape_summarize()
    local totalCount = 0
    local strikeCount = 0
    local min, max = 0, 0

    local histogram = {}

    for k, v in next, strikes do
        local fontID = round(k / 1000)
        local size = k - fontID * 1000
        local count = array_count(v)

--        io.write("fontID,", fontID, ", size,", size, ", entries,", count, "\n");

        min = math.min(min, count)
        max = math.max(max, count)
        totalCount = totalCount + count
        strikeCount = strikeCount + 1

        histogram[count] = (histogram[count] or 0) + 1
    end
    local ave = round(totalCount / strikeCount)

    io.write("\n", "unique glyphs: min = ", min, ", max = ", max, ", ave = ", ave, "\n");

    for k, v in next, histogram do
        io.write("glyph_count,", k, ",frequency,", v, "\n")
    end
end

function test_summary()
    io.write("just testing test_summary\n")
end

function summarize_unique_glyphIDs()
    io.write("/* runs of unique glyph IDs, with a -1 sentinel between different runs */\n")
    io.write("static const int gUniqueGlyphIDs[] = {\n");
    for k, v in next, strikes do
        dump_array_as_C(bools_to_values(v))
    end
    io.write("-1 };\n")
end


dumpops

function tostr(t)
    local str = ""
    for k, v in next, t do
        if #str > 0 then
            str = str .. ", "
        end
        if type(k) == "number" then
            str = str .. "[" .. k .. "] = "
        else
            str = str .. tostring(k) .. " = "
        end
        if type(v) == "table" then
            str = str .. "{ " .. tostr(v) .. " }"
        else
            str = str .. tostring(v)
        end
    end
    return str
end

function sk_scrape_startcanvas(c, fileName) end

function sk_scrape_endcanvas(c, fileName) end

function sk_scrape_accumulate(t)
    -- dump the params in t, specifically showing the verb first, which we
    -- then nil out so it doesn't appear in tostr()
    io.write(t.verb, " ")
    t.verb = nil
    io.write(tostr(t), "\n")
end

function sk_scrape_summarize() end


#!/usr/bin/env lua

local format_br = '\n.br\n'
local tools = {
	"wasm-decompile",	"wasm-interp",	"wasm-objdump",	"wasm-opcodecnt",
	"wasm-strip",	"wasm-validate",	"wasm2c",	"wasm2wat",
	"wast2json",	"wat-desugar",	"wat2wasm",	"spectest-interp"
}

local name, mainarg, argvs
local usage
local short = ""
local full = {}
local examples = {}
local options = {}

local last = { }

do -- parse usage
	local usage = io.read('*line');
	name, mainarg, argvs = usage:match("usage: ([^%s%c]+) %[options%] ([^%s%c]+) %[([^%s%c]+)%]%.%.%.")
	if not argvs then
		name, mainarg = usage:match("usage: ([^%s%c]+) %[options%] ([^%s%c]+)")
	end
end

do -- read short description
	repeat line = io.read('*line');
		short = short .. ' ' .. line
	until line == ""
end

do -- read full description
	repeat line = io.read('*line');
		table.insert(full, line)
	until line == "examples:"
	do -- format full description
		table.remove(full, #full) -- remove "examples:"
		full = table.concat(full, "") -- concat everything with a space
		full = full:gsub("^  ", "")
		full = full:gsub("\n  ", "")
		-- full = full:gsub("  +", "\n")
		full:gsub('\n', format_br)
	end
end

do -- parse examples
	line = io.read('*line'); -- skip "examples:"
	last = { descr = {} } -- prepare new example
	while line ~= "options:" do
		-- empty lines are between examples
		if line:match("^%s*$") then
			-- format last
			local descr = last.descr
			descr = table.concat(descr, '\n')
			last.descr = descr
			-- push last
			table.insert(examples, last)
			-- prepare new example
			last = { descr = {} }
		end

		-- found the sample usage
		if line:match("^%s*%$ ") then
			last.input = line:match("^ *%$ (.+)")
		end
		-- found some description
		if line:match("^ *# ") then
			table.insert(last.descr, (line:gsub("^ *# ", "")))
		end

		line = io.read('*line');
	end
end

do -- parse options
	last = { }
	for line in io.stdin:lines() do
		if line:match("^ +%-") then
			table.insert(options, last)

			local short, long, descr = line:match("^  %-(%w), %-%-([^%s%c]+) +(.+)")
			if not short then
				long, descr = line:match("^      %-%-([^%s%c]+) +(.+)")
			end
			last = {
				short = short,
				long = long,
				descr = descr,
			}
		else
			last.descr = last.descr .. line:gsub("^ +", "\n")
		end
	end
	table.remove(options, 1)
	last = { }
end

-- remove this tool from the SEE ALSO section
for index, tool in pairs(tools) do
	if tool == name then
		table.remove(tools, index)
		break
	end
end

do -- print the man page
	print(".Dd $Mdocdate$")
	print(".Os")
	print(".Sh NAME")
	print((".Nm %s"):format(name))
	print((".Nd %s"):format(short))
	print(".Sh SYNOPSIS")
	print((".Nm %s"):format(name))
	print(".Op options")
	print((".Ar %s"):format(mainarg))
	if argvs then
		print((".Ar [%s]..."):format(argvs))
	end
	print(".Sh DESCRIPTION")
	print(".Nm")
	print(full)
	print(".Pp")
	print("The options are as follows:")
	print(".Bl -tag -width Ds")
	for index, option in pairs(options) do
		if option.short then
			print((".It Fl %s , Fl Fl %s"):format(option.short, option.long))
		else
			print((".It Fl Fl %s"):format(option.long))
		end
		print(option.descr)
	end
	print(".El")
	print(".Sh EXAMPLES")
	for index, example in pairs(examples) do
		print(example.descr)
		print(".Pp")
		print((".Dl $ %s"):format(example.input))
	end
	print(".Sh SEE ALSO")
	for idx, tool in pairs(tools) do
		print((".Xr %s 1 %s"):format(tool, idx == #tool and "" or ","))
	end
	print(".Sh BUGS")
	print("If you find a bug, please report it at")
	print(".br")
	print(".Lk https://github.com/WebAssembly/wabt/issues .")
end


example

--[[
	Auctioneer Advanced
	Version: <%version%> (<%codename%>)
	Revision: $Id: CoreMain.lua 2233 2007-09-25 03:57:33Z norganna $
	URL: http://auctioneeraddon.com/
	This is an addon for World of Warcraft that adds statistical history to the auction data that is collected
	when the auction is scanned, so that you can easily determine what price
	you will be able to sell an item for at auction or at a vendor whenever you
	mouse-over an item in the game
]]
--[[
	See CoreAPI.lua for a description of the modules API
]]
if (not AucAdvanced) then AucAdvanced = {} end
if (not AucAdvancedData) then AucAdvancedData = {} end
if (not AucAdvancedLocal) then AucAdvancedLocal = {} end
if (not AucAdvancedConfig) then AucAdvancedConfig = {} end
AucAdvanced.Version="<%version%>";
if (AucAdvanced.Version == "<".."%version%>") then
	AucAdvanced.Version = "5.0.DEV";
end
local private = {}
-- For our modular stats system, each stats engine should add their
-- subclass to AucAdvanced.Modules.<type>.<name> and store their data into their own
-- data table in AucAdvancedData.Stats.<type><name>
if (not AucAdvanced.Modules) then AucAdvanced.Modules = {Stat={},Util={},Filter={}} end
if (not AucAdvancedData.Stats) then AucAdvancedData.Stats = {} end
if (not AucAdvancedLocal.Stats) then AucAdvancedLocal.Stats = {} end
function private.TooltipHook(vars, ret, frame, name, hyperlink, quality, quantity, cost, additional)
	if EnhTooltip.LinkType(hyperlink) ~= "item" then
		return -- Auctioneer hooks into item tooltips only
	end
	-- Check to see if we need to force load scandata
	local getter = AucAdvanced.Settings.GetSetting
	if (getter("scandata.tooltip.display") and getter("scandata.force")) then
		AucAdvanced.Scan.GetImage()
	end
	for system, systemMods in pairs(AucAdvanced.Modules) do
		for engine, engineLib in pairs(systemMods) do
			if (engineLib.Processor) then engineLib.Processor("tooltip", frame, name, hyperlink, quality, quantity, cost, additional) end
		end
	end
end
function private.HookAH()
	hooksecurefunc("AuctionFrameBrowse_Update", AucAdvanced.API.ListUpdate)
	for system, systemMods in pairs(AucAdvanced.Modules) do
		for engine, engineLib in pairs(systemMods) do
			if (engineLib.Processor) then
				engineLib.Processor("auctionui")
			end
		end
	end
end
function private.OnLoad(addon)
	addon = addon:lower()
	-- Check if the actual addon itself is loading
	if (addon == "auc-advanced") then
		Stubby.RegisterAddOnHook("Blizzard_AuctionUi", "Auc-Advanced", private.HookAH)
		Stubby.RegisterFunctionHook("EnhTooltip.AddTooltip", 600, private.TooltipHook)
		for pos, module in ipairs(AucAdvanced.EmbeddedModules) do
			-- These embedded modules have also just been loaded
			private.OnLoad(module)
		end
	end
	-- Notify the actual module if it exists
	local auc, sys, eng = strsplit("-", addon)
	if (auc == "auc" and sys and eng) then
		for system, systemMods in pairs(AucAdvanced.Modules) do
			if (sys == system:lower()) then
				for engine, engineLib in pairs(systemMods) do
					if (eng == engine:lower() and engineLib.OnLoad) then
						engineLib.OnLoad(addon)
					end
				end
			end
		end
	end
	-- Check all modules' load triggers and pass event to processors
	for system, systemMods in pairs(AucAdvanced.Modules) do
		for engine, engineLib in pairs(systemMods) do
			if (engineLib.LoadTriggers and engineLib.LoadTriggers[addon]) then
				if (engineLib.OnLoad) then
					engineLib.OnLoad(addon)
				end
			end
			if (engineLib.Processor and auc == "auc" and sys and eng) then
				engineLib.Processor("load", addon)
			end
		end
	end
end
function private.OnUnload()
	for system, systemMods in pairs(AucAdvanced.Modules) do
		for engine, engineLib in pairs(systemMods) do
			if (engineLib.OnUnload) then
				engineLib.OnUnload()
			end
		end
	end
end
private.Schedule = {}
function private.OnEvent(...)
	local event, arg = select(2, ...)
	if (event == "ADDON_LOADED") then
		local addon = string.lower(arg)
		if (addon:sub(1,4) == "auc-") then
			private.OnLoad(addon)
		end
	elseif (event == "AUCTION_HOUSE_SHOW") then
		-- Do Nothing for now
	elseif (event == "AUCTION_HOUSE_CLOSED") then
		AucAdvanced.Scan.Interrupt()
	elseif (event == "PLAYER_LOGOUT") then
		AucAdvanced.Scan.Commit(true)
		private.OnUnload()
	elseif event == "UNIT_INVENTORY_CHANGED"
	or event == "ITEM_LOCK_CHANGED"
	or event == "CURSOR_UPDATE"
	or event == "BAG_UPDATE"
	then
		private.Schedule["inventory"] = GetTime() + 0.15
	end
end
function private.OnUpdate(...)
	if event == "inventory" then
		AucAdvanced.Post.AlertBagsChanged()
	end
	local now = GetTime()
	for event, time in pairs(private.Schedule) do
		if time > now then
			for system, systemMods in pairs(AucAdvanced.Modules) do
				for engine, engineLib in pairs(systemMods) do
					if engineLib.Processor then
						engineLib.Processor(event, time)
					end
				end
			end
		end
		private.Schedule[event] = nil
	end
end
private.Frame = CreateFrame("Frame")
private.Frame:RegisterEvent("ADDON_LOADED")
private.Frame:RegisterEvent("AUCTION_HOUSE_SHOW")
private.Frame:RegisterEvent("AUCTION_HOUSE_CLOSED")
private.Frame:RegisterEvent("UNIT_INVENTORY_CHANGED")
private.Frame:RegisterEvent("ITEM_LOCK_CHANGED")
private.Frame:RegisterEvent("CURSOR_UPDATE")
private.Frame:RegisterEvent("BAG_UPDATE")
private.Frame:RegisterEvent("PLAYER_LOGOUT")
private.Frame:SetScript("OnEvent", private.OnEvent)
private.Frame:SetScript("OnUpdate", private.OnUpdate)
-- Auctioneer's debug functions
AucAdvanced.Debug = {}
local addonName = "Auctioneer" -- the addon's name as it will be displayed in
                               -- the debug messages
-------------------------------------------------------------------------------
-- Prints the specified message to nLog.
--
-- syntax:
--    errorCode, message = debugPrint([message][, category][, title][, errorCode][, level])
--
-- parameters:
--    message   - (string) the error message
--                nil, no error message specified
--    category  - (string) the category of the debug message
--                nil, no category specified
--    title     - (string) the title for the debug message
--                nil, no title specified
--    errorCode - (number) the error code
--                nil, no error code specified
--    level     - (string) nLog message level
--                         Any nLog.levels string is valid.
--                nil, no level specified
--
-- returns:
--    errorCode - (number) errorCode, if one is specified
--                nil, otherwise
--    message   - (string) message, if one is specified
--                nil, otherwise
-------------------------------------------------------------------------------
function AucAdvanced.Debug.DebugPrint(message, category, title, errorCode, level)
	return DebugLib.DebugPrint(addonName, message, category, title, errorCode, level)
end
-------------------------------------------------------------------------------
-- Used to make sure that conditions are met within functions.
-- If test is false, the error message will be written to nLog and the user's
-- default chat channel.
--
-- syntax:
--    assertion = assert(test, message)
--
-- parameters:
--    test    - (any)     false/nil, if the assertion failed
--                        anything else, otherwise
--    message - (string)  the message which will be output to the user
--
-- returns:
--    assertion - (boolean) true, if the test passed
--                          false, otherwise
-------------------------------------------------------------------------------
function AucAdvanced.Debug.Assert(test, message)
	return DebugLib.Assert(addonName, test, message)
end


scimark

------------------------------------------------------------------------------
-- Lua SciMark (2010-12-20).
--
-- A literal translation of SciMark 2.0a, written in Java and C.
-- Credits go to the original authors Roldan Pozo and Bruce Miller.
-- See: http://math.nist.gov/scimark2/
------------------------------------------------------------------------------
local SCIMARK_VERSION = "2010-12-10"
local MIN_TIME = 2.0
local RANDOM_SEED = 101009 -- Must be odd.
local SIZE_SELECT = "small"
local benchmarks = {
  "FFT", "SOR", "MC", "SPARSE", "LU",
  small = {
    FFT		= { 1024 },
    SOR		= { 100 },
    MC		= { },
    SPARSE	= { 1000, 5000 },
    LU		= { 100 },
  },
  large = {
    FFT		= { 1048576 },
    SOR		= { 1000 },
    MC		= { },
    SPARSE	= { 100000, 1000000 },
    LU		= { 1000 },
  },
}
local abs, log, sin, floor = math.abs, math.log, math.sin, math.floor
local pi, clock = math.pi, os.clock
local format = string.format
------------------------------------------------------------------------------
-- Select array type: Lua tables or native (FFI) arrays
------------------------------------------------------------------------------
local darray, iarray
local function array_init()
  if jit and jit.status and jit.status() then
    local ok, ffi = pcall(require, "ffi")
    if ok then
      darray = ffi.typeof("double[?]")
      iarray = ffi.typeof("int[?]")
      return
    end
  end
  function darray(n) return {} end
  iarray = darray
end
------------------------------------------------------------------------------
-- This is a Lagged Fibonacci Pseudo-random Number Generator with
-- j, k, M = 5, 17, 31. Pretty weak, but same as C/Java SciMark.
------------------------------------------------------------------------------
local rand, rand_init
if jit and jit.status and jit.status() then
  -- LJ2 has bit operations and zero-based arrays (internally).
  local bit = require("bit")
  local band, sar = bit.band, bit.arshift
  function rand_init(seed)
    local Rm, Rj, Ri = iarray(17), 16, 11
    for i=0,16 do Rm[i] = 0 end
    for i=16,0,-1 do
      seed = band(seed*9069, 0x7fffffff)
      Rm[i] = seed
    end
    function rand()
      local i = band(Ri+1, sar(Ri-16, 31))
      local j = band(Rj+1, sar(Rj-16, 31))
      Ri, Rj = i, j
      local k = band(Rm[i] - Rm[j], 0x7fffffff)
      Rm[j] = k
      return k * (1.0/2147483647.0)
    end
  end
else
  -- Better for standard Lua with one-based arrays and without bit operations.
  function rand_init(seed)
    local Rm, Rj = {}, 1
    for i=1,17 do Rm[i] = 0 end
    for i=17,1,-1 do
      seed = (seed*9069) % (2^31)
      Rm[i] = seed
    end
    function rand()
      local j, m = Rj, Rm
      local h = j - 5
      if h < 1 then h = h + 17 end
      local k = m[h] - m[j]
      if k < 0 then k = k + 2147483647 end
      m[j] = k
      if j < 17 then Rj = j + 1 else Rj = 1 end
      return k * (1.0/2147483647.0)
    end
  end
end
local function random_vector(n)
  local v = darray(n+1)
  for x=1,n do v[x] = rand() end
  return v
end
local function random_matrix(m, n)
  local a = {}
  for y=1,m do
    local v = darray(n+1)
    a[y] = v
    for x=1,n do v[x] = rand() end
  end
  return a
end
------------------------------------------------------------------------------
-- FFT: Fast Fourier Transform.
------------------------------------------------------------------------------
local function fft_bitreverse(v, n)
  local j = 0
  for i=0,2*n-4,2 do
    if i < j then
      v[i+1], v[i+2], v[j+1], v[j+2] = v[j+1], v[j+2], v[i+1], v[i+2]
    end
    local k = n
    while k <= j do j = j - k; k = k / 2 end
    j = j + k
  end
end
local function fft_transform(v, n, dir)
  if n <= 1 then return end
  fft_bitreverse(v, n)
  local dual = 1
  repeat
    local dual2 = 2*dual
    for i=1,2*n-1,2*dual2 do
      local j = i+dual2
      local ir, ii = v[i], v[i+1]
      local jr, ji = v[j], v[j+1]
      v[j], v[j+1] = ir - jr, ii - ji
      v[i], v[i+1] = ir + jr, ii + ji
    end
    local theta = dir * pi / dual
    local s, s2 = sin(theta), 2.0 * sin(theta * 0.5)^2
    local wr, wi = 1.0, 0.0
    for a=3,dual2-1,2 do
      wr, wi = wr - s*wi - s2*wr, wi + s*wr - s2*wi
      for i=a,a+2*(n-dual2),2*dual2 do
	local j = i+dual2
	local jr, ji = v[j], v[j+1]
	local dr, di = wr*jr - wi*ji, wr*ji + wi*jr
	local ir, ii = v[i], v[i+1]
	v[j], v[j+1] = ir - dr, ii - di
	v[i], v[i+1] = ir + dr, ii + di
      end
    end
    dual = dual2
  until dual >= n
end
function benchmarks.FFT(n)
  local l2n = log(n)/log(2)
  if l2n % 1 ~= 0 then
    io.stderr:write("Error: FFT data length is not a power of 2\n")
    os.exit(1)
  end
  local v = random_vector(n*2)
  return function(cycles)
    local norm = 1.0 / n
    for p=1,cycles do
      fft_transform(v, n, -1)
      fft_transform(v, n, 1)
      for i=1,n*2 do v[i] = v[i] * norm end
    end
    return ((5*n-2)*l2n + 2*(n+1)) * cycles
  end
end
------------------------------------------------------------------------------
-- SOR: Jacobi Successive Over-Relaxation.
------------------------------------------------------------------------------
local function sor_run(mat, m, n, cycles, omega)
  local om4, om1 = omega*0.25, 1.0-omega
  m = m - 1
  n = n - 1
  for i=1,cycles do
    for y=2,m do
      local v, vp, vn = mat[y], mat[y-1], mat[y+1]
      for x=2,n do
	v[x] = om4*((vp[x]+vn[x])+(v[x-1]+v[x+1])) + om1*v[x]
      end
    end
  end
end
function benchmarks.SOR(n)
  local mat = random_matrix(n, n)
  return function(cycles)
    sor_run(mat, n, n, cycles, 1.25)
    return (n-1)*(n-1)*cycles*6
  end
end
------------------------------------------------------------------------------
-- MC: Monte Carlo Integration.
------------------------------------------------------------------------------
local function mc_integrate(cycles)
  local under_curve = 0
  local rand = rand
  for i=1,cycles do
    local x = rand()
    local y = rand()
    if x*x + y*y <= 1.0 then under_curve = under_curve + 1 end
  end
  return (under_curve/cycles) * 4
end
function benchmarks.MC()
  return function(cycles)
    local res = mc_integrate(cycles)
    assert(math.sqrt(cycles)*math.abs(res-math.pi) < 5.0, "bad MC result")
    return cycles * 4 -- Way off, but same as SciMark in C/Java.
  end
end
------------------------------------------------------------------------------
-- Sparse Matrix Multiplication.
------------------------------------------------------------------------------
local function sparse_mult(n, cycles, vy, val, row, col, vx)
  for p=1,cycles do
    for r=1,n do
      local sum = 0
      for i=row[r],row[r+1]-1 do sum = sum + vx[col[i]] * val[i] end
      vy[r] = sum
    end
  end
end
function benchmarks.SPARSE(n, nz)
  local nr = floor(nz/n)
  local anz = nr*n
  local vx = random_vector(n)
  local val = random_vector(anz)
  local vy, col, row = darray(n+1), iarray(nz+1), iarray(n+2)
  row[1] = 1
  for r=1,n do
    local step = floor(r/nr)
    if step < 1 then step = 1 end
    local rr = row[r]
    row[r+1] = rr+nr
    for i=0,nr-1 do col[rr+i] = 1+i*step end
  end
  return function(cycles)
    sparse_mult(n, cycles, vy, val, row, col, vx)
    return anz*cycles*2
  end
end
------------------------------------------------------------------------------
-- LU: Dense Matrix Factorization.
------------------------------------------------------------------------------
local function lu_factor(a, pivot, m, n)
  local min_m_n = m < n and m or n
  for j=1,min_m_n do
    local jp, t = j, abs(a[j][j])
    for i=j+1,m do
      local ab = abs(a[i][j])
      if ab > t then
	jp = i
	t = ab
      end
    end
    pivot[j] = jp
    if a[jp][j] == 0 then error("zero pivot") end
    if jp ~= j then a[j], a[jp] = a[jp], a[j] end
    if j < m then
      local recp = 1.0 / a[j][j]
      for k=j+1,m do
	local v = a[k]
	v[j] = v[j] * recp
      end
    end
    if j < min_m_n then
      for i=j+1,m do
	local vi, vj = a[i], a[j]
	local eij = vi[j]
	for k=j+1,n do vi[k] = vi[k] - eij * vj[k] end
      end
    end
  end
end
local function matrix_alloc(m, n)
  local a = {}
  for y=1,m do a[y] = darray(n+1) end
  return a
end
local function matrix_copy(dst, src, m, n)
  for y=1,m do
    local vd, vs = dst[y], src[y]
    for x=1,n do vd[x] = vs[x] end
  end
end
function benchmarks.LU(n)
  local mat = random_matrix(n, n)
  local tmp = matrix_alloc(n, n)
  local pivot = iarray(n+1)
  return function(cycles)
    for i=1,cycles do
      matrix_copy(tmp, mat, n, n)
      lu_factor(tmp, pivot, n, n)
    end
    return 2.0/3.0*n*n*n*cycles
  end
end
------------------------------------------------------------------------------
-- Main program.
------------------------------------------------------------------------------
local function printf(...)
  io.write(format(...))
end
local function fmtparams(p1, p2)
  if p2 then return format("[%d, %d]", p1, p2)
  elseif p1 then return format("[%d]", p1) end
  return ""
end
local function measure(min_time, name, ...)
  array_init()
  rand_init(RANDOM_SEED)
  local run = benchmarks[name](...)
  local cycles = 1
  repeat
    local tm = clock()
    local flops = run(cycles, ...)
    tm = clock() - tm
    if tm >= min_time then
      local res = flops / tm * 1.0e-6
      local p1, p2 = ...
      printf("%-7s %8.2f  %s\n", name, res, fmtparams(...))
      return res
    end
    cycles = cycles * 2
  until false
end
printf("Lua SciMark %s based on SciMark 2.0a. %s.\n\n",
while arg and arg[1] do
  local a = table.remove(arg, 1)
  if a == "-noffi" then
    package.preload.ffi = nil
  elseif a == "-small" then
    SIZE_SELECT = "small"
  elseif a == "-large" then
    SIZE_SELECT = "large"
  elseif benchmarks[a] then
    local p = benchmarks[SIZE_SELECT][a]
    measure(MIN_TIME, a, tonumber(arg[1]) or p[1], tonumber(arg[2]) or p[2])
    return
  else
    printf("Usage: scimark [-noffi] [-small|-large] [BENCH params...]\n\n")
    printf("BENCH   -small         -large\n")
    printf("---------------------------------------\n")
    for _,name in ipairs(benchmarks) do
      printf("%-7s %-13s %s\n", name,
	     fmtparams(unpack(benchmarks.small[name])),
	     fmtparams(unpack(benchmarks.large[name])))
    end
    printf("\n")
    os.exit(1)
  end
end
local params = benchmarks[SIZE_SELECT]
local sum = 0
for _,name in ipairs(benchmarks) do
  -- change unpack to table.unpack; compatible with lua5.3
  sum = sum + measure(MIN_TIME, name, table.unpack(params[name]))
end
printf("\nSciMark %8.2f  [%s problem sizes]\n", sum / #benchmarks, SIZE_SELECT)
io.flush()


binarytrees

-- The Computer Language Benchmarks Game
-- http://benchmarksgame.alioth.debian.org/
-- contributed by Mike Pall
local function BottomUpTree(item, depth)
  if depth > 0 then
    local i = item + item
    depth = depth - 1
    local left, right = BottomUpTree(i-1, depth), BottomUpTree(i, depth)
    return { item, left, right }
  else
    return { item }
  end
end
local function ItemCheck(tree)
  if tree[2] then
    return tree[1] + ItemCheck(tree[2]) - ItemCheck(tree[3])
  else
    return tree[1]
  end
end
local N = tonumber(arg and arg[1]) or 0
local mindepth = 4
local maxdepth = mindepth + 2
if maxdepth < N then maxdepth = N end
do
  local stretchdepth = maxdepth + 1
  local stretchtree = BottomUpTree(0, stretchdepth)
  io.write(string.format("stretch tree of depth %d\t check: %d\n",
    stretchdepth, ItemCheck(stretchtree)))
end
local longlivedtree = BottomUpTree(0, maxdepth)
for depth=mindepth,maxdepth,2 do
  local iterations = 2 ^ (maxdepth - depth + mindepth)
  local check = 0
  for i=1,iterations do
    check = check + ItemCheck(BottomUpTree(1, depth)) +
            ItemCheck(BottomUpTree(-1, depth))
  end
  io.write(string.format("%d\t trees of depth %d\t check: %d\n",
    iterations*2, depth, check))
end
io.write(string.format("long lived tree of depth %d\t check: %d\n",
  maxdepth, ItemCheck(longlivedtree)))


-- need to update the Lua path to point to the local flatbuffers implementation
package.path = string.format("../lua/?.lua;%s",package.path)
package.path = string.format("./lua/?.lua;%s",package.path)

-- require the library
local flatbuffers = require("flatbuffers")

local binaryArray = flatbuffers.binaryArray-- for hex dump utility

-- require the files generated from the schema
local weapon = require("MyGame.Sample.Weapon")
local monster = require("MyGame.Sample.Monster")
local vec3 = require("MyGame.Sample.Vec3")
local color = require("MyGame.Sample.Color")
local equipment = require("MyGame.Sample.Equipment")

-- get access to the builder, providing an array of size 1024
local builder = flatbuffers.Builder(1024)

local weaponOne = builder:CreateString("Sword")
local weaponTwo = builder:CreateString("Axe")

-- Create the first 'Weapon'
weapon.Start(builder)
weapon.AddName(builder, weaponOne)
weapon.AddDamage(builder, 3)
local sword = weapon.End(builder)

-- Create the second 'Weapon'
weapon.Start(builder)
weapon.AddName(builder, weaponTwo)
weapon.AddDamage(builder, 5)
local axe = weapon.End(builder)

-- Serialize a name for our mosnter, called 'orc'
local name = builder:CreateString("Orc")

-- Create a `vector` representing the inventory of the Orc. Each number
-- could correspond to an item that can be claimed after he is slain.
-- Note: Since we prepend the bytes, this loop iterates in reverse.
monster.StartInventoryVector(builder, 10)
for i=10,1,-1 do
    builder:PrependByte(i)
end
local inv = builder:EndVector(10)

-- Create a FlatBuffer vector and prepend the weapons.
-- Note: Since we prepend the data, prepend them in reverse order.
monster.StartWeaponsVector(builder, 2)
builder:PrependUOffsetTRelative(axe)
builder:PrependUOffsetTRelative(sword)
local weapons = builder:EndVector(2)

-- Create our monster by using Start() andEnd()
monster.Start(builder)
monster.AddPos(builder, vec3.CreateVec3(builder, 1.0, 2.0, 3.0))
monster.AddHp(builder, 300)
monster.AddName(builder, name)
monster.AddInventory(builder, inv)
monster.AddColor(builder, color.Red)
monster.AddWeapons(builder, weapons)
monster.AddEquippedType(builder, equipment.Weapon)
monster.AddEquipped(builder, axe)
local orc = monster.End(builder)

-- Call 'Finish()' to instruct the builder that this monster is complete.
builder:Finish(orc)

-- Get the flatbuffer as a string containing the binary data
local bufAsString = builder:Output()

-- Convert the string representation into binary array Lua structure
local buf = flatbuffers.binaryArray.New(bufAsString)

-- Get an accessor to the root object insert the buffer
local mon = monster.GetRootAsMonster(buf, 0)

assert(mon:Mana() == 150)
assert(mon:Hp() == 300)
assert(mon:Name() == "Orc")
assert(mon:Color() == color.Red)
assert(mon:Pos():X() == 1.0)
assert(mon:Pos():Y() == 2.0)
assert(mon:Pos():Z() == 3.0)

for i=1,mon:InventoryLength() do
    assert(mon:Inventory(i) == i)
end

local expected = {
    {w = 'Sword', d = 3},
    {w = 'Axe', d = 5}
}

for i=1,mon:WeaponsLength() do
   assert(mon:Weapons(i):Name() == expected[i].w)
   assert(mon:Weapons(i):Damage() == expected[i].d)
end

assert(mon:EquippedType() == equipment.Weapon)

local unionWeapon = weapon.New()
unionWeapon:Init(mon:Equipped().bytes,mon:Equipped().pos)
assert(unionWeapon:Name() == "Axe")
assert(unionWeapon:Damage() == 5)

print("The Lua FlatBuffer example was successfully created and verified!")


Equipment

-- automatically generated by the FlatBuffers compiler, do not modify

-- namespace: Sample

local Equipment = {
    NONE = 0,
    Weapon = 1,
}

return Equipment -- return the module


Monster

-- automatically generated by the FlatBuffers compiler, do not modify

-- namespace: Sample

local flatbuffers = require('flatbuffers')

local Monster = {} -- the module
local Monster_mt = {} -- the class metatable

function Monster.New()
    local o = {}
    setmetatable(o, {__index = Monster_mt})
    return o
end
function Monster.GetRootAsMonster(buf, offset)
    local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
    local o = Monster.New()
    o:Init(buf, n + offset)
    return o
end
function Monster_mt:Init(buf, pos)
    self.view = flatbuffers.view.New(buf, pos)
end
function Monster_mt:Pos()
    local o = self.view:Offset(4)
    if o ~= 0 then
        local x = o + self.view.pos
        local obj = require('MyGame.Sample.Vec3').New()
        obj:Init(self.view.bytes, x)
        return obj
    end
end
function Monster_mt:Mana()
    local o = self.view:Offset(6)
    if o ~= 0 then
        return self.view:Get(flatbuffers.N.Int16, o + self.view.pos)
    end
    return 150
end
function Monster_mt:Hp()
    local o = self.view:Offset(8)
    if o ~= 0 then
        return self.view:Get(flatbuffers.N.Int16, o + self.view.pos)
    end
    return 100
end
function Monster_mt:Name()
    local o = self.view:Offset(10)
    if o ~= 0 then
        return self.view:String(o + self.view.pos)
    end
end
function Monster_mt:Inventory(j)
    local o = self.view:Offset(14)
    if o ~= 0 then
        local a = self.view:Vector(o)
        return self.view:Get(flatbuffers.N.Uint8, a + ((j-1) * 1))
    end
    return 0
end
function Monster_mt:InventoryLength()
    local o = self.view:Offset(14)
    if o ~= 0 then
        return self.view:VectorLen(o)
    end
    return 0
end
function Monster_mt:Color()
    local o = self.view:Offset(16)
    if o ~= 0 then
        return self.view:Get(flatbuffers.N.Int8, o + self.view.pos)
    end
    return 2
end
function Monster_mt:Weapons(j)
    local o = self.view:Offset(18)
    if o ~= 0 then
        local x = self.view:Vector(o)
        x = x + ((j-1) * 4)
        x = self.view:Indirect(x)
        local obj = require('MyGame.Sample.Weapon').New()
        obj:Init(self.view.bytes, x)
        return obj
    end
end
function Monster_mt:WeaponsLength()
    local o = self.view:Offset(18)
    if o ~= 0 then
        return self.view:VectorLen(o)
    end
    return 0
end
function Monster_mt:EquippedType()
    local o = self.view:Offset(20)
    if o ~= 0 then
        return self.view:Get(flatbuffers.N.Uint8, o + self.view.pos)
    end
    return 0
end
function Monster_mt:Equipped()
    local o = self.view:Offset(22)
    if o ~= 0 then
        local obj = flatbuffers.view.New(require('flatbuffers.binaryarray').New(0), 0)
        self.view:Union(obj, o)
        return obj
    end
end
function Monster.Start(builder) builder:StartObject(10) end
function Monster.AddPos(builder, pos) builder:PrependStructSlot(0, pos, 0) end
function Monster.AddMana(builder, mana) builder:PrependInt16Slot(1, mana, 150) end
function Monster.AddHp(builder, hp) builder:PrependInt16Slot(2, hp, 100) end
function Monster.AddName(builder, name) builder:PrependUOffsetTRelativeSlot(3, name, 0) end
function Monster.AddInventory(builder, inventory) builder:PrependUOffsetTRelativeSlot(5, inventory, 0) end
function Monster.StartInventoryVector(builder, numElems) return builder:StartVector(1, numElems, 1) end
function Monster.AddColor(builder, color) builder:PrependInt8Slot(6, color, 2) end
function Monster.AddWeapons(builder, weapons) builder:PrependUOffsetTRelativeSlot(7, weapons, 0) end
function Monster.StartWeaponsVector(builder, numElems) return builder:StartVector(4, numElems, 4) end
function Monster.AddEquippedType(builder, equippedType) builder:PrependUint8Slot(8, equippedType, 0) end
function Monster.AddEquipped(builder, equipped) builder:PrependUOffsetTRelativeSlot(9, equipped, 0) end
function Monster.End(builder) return builder:EndObject() end

return Monster -- return the module


Weapon

-- automatically generated by the FlatBuffers compiler, do not modify

-- namespace: Sample

local flatbuffers = require('flatbuffers')

local Weapon = {} -- the module
local Weapon_mt = {} -- the class metatable

function Weapon.New()
    local o = {}
    setmetatable(o, {__index = Weapon_mt})
    return o
end
function Weapon.GetRootAsWeapon(buf, offset)
    local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
    local o = Weapon.New()
    o:Init(buf, n + offset)
    return o
end
function Weapon_mt:Init(buf, pos)
    self.view = flatbuffers.view.New(buf, pos)
end
function Weapon_mt:Name()
    local o = self.view:Offset(4)
    if o ~= 0 then
        return self.view:String(o + self.view.pos)
    end
end
function Weapon_mt:Damage()
    local o = self.view:Offset(6)
    if o ~= 0 then
        return self.view:Get(flatbuffers.N.Int16, o + self.view.pos)
    end
    return 0
end
function Weapon.Start(builder) builder:StartObject(2) end
function Weapon.AddName(builder, name) builder:PrependUOffsetTRelativeSlot(0, name, 0) end
function Weapon.AddDamage(builder, damage) builder:PrependInt16Slot(1, damage, 0) end
function Weapon.End(builder) return builder:EndObject() end

return Weapon -- return the module


-- automatically generated by the FlatBuffers compiler, do not modify

-- namespace: Sample

local flatbuffers = require('flatbuffers')

local Vec3 = {} -- the module
local Vec3_mt = {} -- the class metatable

function Vec3.New()
    local o = {}
    setmetatable(o, {__index = Vec3_mt})
    return o
end
function Vec3_mt:Init(buf, pos)
    self.view = flatbuffers.view.New(buf, pos)
end
function Vec3_mt:X()
    return self.view:Get(flatbuffers.N.Float32, self.view.pos + 0)
end
function Vec3_mt:Y()
    return self.view:Get(flatbuffers.N.Float32, self.view.pos + 4)
end
function Vec3_mt:Z()
    return self.view:Get(flatbuffers.N.Float32, self.view.pos + 8)
end
function Vec3.CreateVec3(builder, x, y, z)
    builder:Prep(4, 12)
    builder:PrependFloat32(z)
    builder:PrependFloat32(y)
    builder:PrependFloat32(x)
    return builder:Offset()
end

return Vec3 -- return the module


Color

-- automatically generated by the FlatBuffers compiler, do not modify

-- namespace: Sample

local Color = {
    Red = 0,
    Green = 1,
    Blue = 2,
}

return Color -- return the module


SecondTableInA

-- automatically generated by the FlatBuffers compiler, do not modify

-- namespace: NamespaceA

local flatbuffers = require('flatbuffers')

local SecondTableInA = {} -- the module
local SecondTableInA_mt = {} -- the class metatable

function SecondTableInA.New()
    local o = {}
    setmetatable(o, {__index = SecondTableInA_mt})
    return o
end
function SecondTableInA.GetRootAsSecondTableInA(buf, offset)
    if type(buf) == "string" then
        buf = flatbuffers.binaryArray.New(buf)
    end
    local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
    local o = SecondTableInA.New()
    o:Init(buf, n + offset)
    return o
end
function SecondTableInA_mt:Init(buf, pos)
    self.view = flatbuffers.view.New(buf, pos)
end
function SecondTableInA_mt:ReferToC()
    local o = self.view:Offset(4)
    if o ~= 0 then
        local x = self.view:Indirect(o + self.view.pos)
        local obj = require('NamespaceC.TableInC').New()
        obj:Init(self.view.bytes, x)
        return obj
    end
end
function SecondTableInA.Start(builder) builder:StartObject(1) end
function SecondTableInA.AddReferToC(builder, referToC) builder:PrependUOffsetTRelativeSlot(0, referToC, 0) end
function SecondTableInA.End(builder) return builder:EndObject() end

return SecondTableInA -- return the module


TableInFirstNS

-- automatically generated by the FlatBuffers compiler, do not modify

-- namespace: NamespaceA

local flatbuffers = require('flatbuffers')

local TableInFirstNS = {} -- the module
local TableInFirstNS_mt = {} -- the class metatable

function TableInFirstNS.New()
    local o = {}
    setmetatable(o, {__index = TableInFirstNS_mt})
    return o
end
function TableInFirstNS.GetRootAsTableInFirstNS(buf, offset)
    if type(buf) == "string" then
        buf = flatbuffers.binaryArray.New(buf)
    end
    local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
    local o = TableInFirstNS.New()
    o:Init(buf, n + offset)
    return o
end
function TableInFirstNS_mt:Init(buf, pos)
    self.view = flatbuffers.view.New(buf, pos)
end
function TableInFirstNS_mt:FooTable()
    local o = self.view:Offset(4)
    if o ~= 0 then
        local x = self.view:Indirect(o + self.view.pos)
        local obj = require('NamespaceA.NamespaceB.TableInNestedNS').New()
        obj:Init(self.view.bytes, x)
        return obj
    end
end
function TableInFirstNS_mt:FooEnum()
    local o = self.view:Offset(6)
    if o ~= 0 then
        return self.view:Get(flatbuffers.N.Int8, o + self.view.pos)
    end
    return 0
end
function TableInFirstNS_mt:FooUnionType()
    local o = self.view:Offset(8)
    if o ~= 0 then
        return self.view:Get(flatbuffers.N.Uint8, o + self.view.pos)
    end
    return 0
end
function TableInFirstNS_mt:FooUnion()
    local o = self.view:Offset(10)
    if o ~= 0 then
        local obj = flatbuffers.view.New(require('flatbuffers.binaryarray').New(0), 0)
        self.view:Union(obj, o)
        return obj
    end
end
function TableInFirstNS_mt:FooStruct()
    local o = self.view:Offset(12)
    if o ~= 0 then
        local x = o + self.view.pos
        local obj = require('NamespaceA.NamespaceB.StructInNestedNS').New()
        obj:Init(self.view.bytes, x)
        return obj
    end
end
function TableInFirstNS.Start(builder) builder:StartObject(5) end
function TableInFirstNS.AddFooTable(builder, fooTable) builder:PrependUOffsetTRelativeSlot(0, fooTable, 0) end
function TableInFirstNS.AddFooEnum(builder, fooEnum) builder:PrependInt8Slot(1, fooEnum, 0) end
function TableInFirstNS.AddFooUnionType(builder, fooUnionType) builder:PrependUint8Slot(2, fooUnionType, 0) end
function TableInFirstNS.AddFooUnion(builder, fooUnion) builder:PrependUOffsetTRelativeSlot(3, fooUnion, 0) end
function TableInFirstNS.AddFooStruct(builder, fooStruct) builder:PrependStructSlot(4, fooStruct, 0) end
function TableInFirstNS.End(builder) return builder:EndObject() end

return TableInFirstNS -- return the module


UnionInNestedNS

-- automatically generated by the FlatBuffers compiler, do not modify

-- namespace: NamespaceB

local UnionInNestedNS = {
    NONE = 0,
    TableInNestedNS = 1,
}

return UnionInNestedNS -- return the module


TableInNestedNS

-- automatically generated by the FlatBuffers compiler, do not modify

-- namespace: NamespaceB

local flatbuffers = require('flatbuffers')

local TableInNestedNS = {} -- the module
local TableInNestedNS_mt = {} -- the class metatable

function TableInNestedNS.New()
    local o = {}
    setmetatable(o, {__index = TableInNestedNS_mt})
    return o
end
function TableInNestedNS.GetRootAsTableInNestedNS(buf, offset)
    if type(buf) == "string" then
        buf = flatbuffers.binaryArray.New(buf)
    end
    local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
    local o = TableInNestedNS.New()
    o:Init(buf, n + offset)
    return o
end
function TableInNestedNS_mt:Init(buf, pos)
    self.view = flatbuffers.view.New(buf, pos)
end
function TableInNestedNS_mt:Foo()
    local o = self.view:Offset(4)
    if o ~= 0 then
        return self.view:Get(flatbuffers.N.Int32, o + self.view.pos)
    end
    return 0
end
function TableInNestedNS.Start(builder) builder:StartObject(1) end
function TableInNestedNS.AddFoo(builder, foo) builder:PrependInt32Slot(0, foo, 0) end
function TableInNestedNS.End(builder) return builder:EndObject() end

return TableInNestedNS -- return the module


StructInNestedNS

-- automatically generated by the FlatBuffers compiler, do not modify

-- namespace: NamespaceB

local flatbuffers = require('flatbuffers')

local StructInNestedNS = {} -- the module
local StructInNestedNS_mt = {} -- the class metatable

function StructInNestedNS.New()
    local o = {}
    setmetatable(o, {__index = StructInNestedNS_mt})
    return o
end
function StructInNestedNS_mt:Init(buf, pos)
    self.view = flatbuffers.view.New(buf, pos)
end
function StructInNestedNS_mt:A()
    return self.view:Get(flatbuffers.N.Int32, self.view.pos + 0)
end
function StructInNestedNS_mt:B()
    return self.view:Get(flatbuffers.N.Int32, self.view.pos + 4)
end
function StructInNestedNS.CreateStructInNestedNS(builder, a, b)
    builder:Prep(4, 8)
    builder:PrependInt32(b)
    builder:PrependInt32(a)
    return builder:Offset()
end

return StructInNestedNS -- return the module


EnumInNestedNS

-- automatically generated by the FlatBuffers compiler, do not modify

-- namespace: NamespaceB

local EnumInNestedNS = {
    A = 0,
    B = 1,
    C = 2,
}

return EnumInNestedNS -- return the module


TableInC

-- automatically generated by the FlatBuffers compiler, do not modify

-- namespace: NamespaceC

local flatbuffers = require('flatbuffers')

local TableInC = {} -- the module
local TableInC_mt = {} -- the class metatable

function TableInC.New()
    local o = {}
    setmetatable(o, {__index = TableInC_mt})
    return o
end
function TableInC.GetRootAsTableInC(buf, offset)
    if type(buf) == "string" then
        buf = flatbuffers.binaryArray.New(buf)
    end
    local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
    local o = TableInC.New()
    o:Init(buf, n + offset)
    return o
end
function TableInC_mt:Init(buf, pos)
    self.view = flatbuffers.view.New(buf, pos)
end
function TableInC_mt:ReferToA1()
    local o = self.view:Offset(4)
    if o ~= 0 then
        local x = self.view:Indirect(o + self.view.pos)
        local obj = require('NamespaceA.TableInFirstNS').New()
        obj:Init(self.view.bytes, x)
        return obj
    end
end
function TableInC_mt:ReferToA2()
    local o = self.view:Offset(6)
    if o ~= 0 then
        local x = self.view:Indirect(o + self.view.pos)
        local obj = require('NamespaceA.SecondTableInA').New()
        obj:Init(self.view.bytes, x)
        return obj
    end
end
function TableInC.Start(builder) builder:StartObject(2) end
function TableInC.AddReferToA1(builder, referToA1) builder:PrependUOffsetTRelativeSlot(0, referToA1, 0) end
function TableInC.AddReferToA2(builder, referToA2) builder:PrependUOffsetTRelativeSlot(1, referToA2, 0) end
function TableInC.End(builder) return builder:EndObject() end

return TableInC -- return the module


InParentNamespace

--[[ MyGame.InParentNamespace

  Automatically generated by the FlatBuffers compiler, do not modify.
  Or modify. I'm a message, not a cop.

  flatc version: 23.5.9

  Declared by  : //monster_test.fbs
  Rooting type : MyGame.Example.Monster (//monster_test.fbs)

--]]

local flatbuffers = require('flatbuffers')

local InParentNamespace = {}
local mt = {}

function InParentNamespace.New()
  local o = {}
  setmetatable(o, {__index = mt})
  return o
end

function mt:Init(buf, pos)
  self.view = flatbuffers.view.New(buf, pos)
end

function InParentNamespace.Start(builder)
  builder:StartObject(0)
end

function InParentNamespace.End(builder)
  return builder:EndObject()
end

return InParentNamespace


Monster

--[[ MyGame.Example2.Monster

  Automatically generated by the FlatBuffers compiler, do not modify.
  Or modify. I'm a message, not a cop.

  flatc version: 23.5.9

  Declared by  : //monster_test.fbs
  Rooting type : MyGame.Example.Monster (//monster_test.fbs)

--]]

local flatbuffers = require('flatbuffers')

local Monster = {}
local mt = {}

function Monster.New()
  local o = {}
  setmetatable(o, {__index = mt})
  return o
end

function mt:Init(buf, pos)
  self.view = flatbuffers.view.New(buf, pos)
end

function Monster.Start(builder)
  builder:StartObject(0)
end

function Monster.End(builder)
  return builder:EndObject()
end

return Monster


Unused

--[[ MyGame.OtherNameSpace.Unused

  Automatically generated by the FlatBuffers compiler, do not modify.
  Or modify. I'm a message, not a cop.

  flatc version: 23.5.9

  Declared by  : //include_test/sub/include_test2.fbs
  Rooting type : MyGame.Example.Monster (//monster_test.fbs)

--]]

local flatbuffers = require('flatbuffers')

local Unused = {}
local mt = {}

function Unused.New()
  local o = {}
  setmetatable(o, {__index = mt})
  return o
end

function mt:Init(buf, pos)
  self.view = flatbuffers.view.New(buf, pos)
end

function mt:A()
  return self.view:Get(flatbuffers.N.Int32, self.view.pos + 0)
end

function Unused.CreateUnused(builder, a)
  builder:Prep(4, 4)
  builder:PrependInt32(a)
  return builder:Offset()
end

return Unused


FromInclude

--[[ MyGame.OtherNameSpace.FromInclude

  Automatically generated by the FlatBuffers compiler, do not modify.
  Or modify. I'm a message, not a cop.

  flatc version: 23.5.9

  Declared by  : //include_test/sub/include_test2.fbs
  Rooting type : MyGame.Example.Monster (//monster_test.fbs)

--]]

local FromInclude = {
  IncludeVal = 0,
}

return FromInclude


TableB

--[[ MyGame.OtherNameSpace.TableB

  Automatically generated by the FlatBuffers compiler, do not modify.
  Or modify. I'm a message, not a cop.

  flatc version: 23.5.9

  Declared by  : //include_test/sub/include_test2.fbs
  Rooting type : MyGame.Example.Monster (//monster_test.fbs)

--]]

local __TableA = require('TableA')
local flatbuffers = require('flatbuffers')

local TableB = {}
local mt = {}

function TableB.New()
  local o = {}
  setmetatable(o, {__index = mt})
  return o
end

function mt:Init(buf, pos)
  self.view = flatbuffers.view.New(buf, pos)
end

function mt:A()
  local o = self.view:Offset(4)
  if o ~= 0 then
    local x = self.view:Indirect(self.view.pos + o)
    local obj = __TableA.New()
    obj:Init(self.view.bytes, x)
    return obj
  end
end

function TableB.Start(builder)
  builder:StartObject(1)
end

function TableB.AddA(builder, a)
  builder:PrependStructSlot(0, a, 0)
end

function TableB.End(builder)
  return builder:EndObject()
end

return TableB


Stat

--[[ MyGame.Example.Stat

  Automatically generated by the FlatBuffers compiler, do not modify.
  Or modify. I'm a message, not a cop.

  flatc version: 23.5.9

  Declared by  : //monster_test.fbs
  Rooting type : MyGame.Example.Monster (//monster_test.fbs)

--]]

local flatbuffers = require('flatbuffers')

local Stat = {}
local mt = {}

function Stat.New()
  local o = {}
  setmetatable(o, {__index = mt})
  return o
end

function mt:Init(buf, pos)
  self.view = flatbuffers.view.New(buf, pos)
end

function mt:Id()
  local o = self.view:Offset(4)
  if o ~= 0 then
    return self.view:String(self.view.pos + o)
  end
end

function mt:Val()
  local o = self.view:Offset(6)
  if o ~= 0 then
    return self.view:Get(flatbuffers.N.Int64, self.view.pos + o)
  end
  return 0
end

function mt:Count()
  local o = self.view:Offset(8)
  if o ~= 0 then
    return self.view:Get(flatbuffers.N.Uint16, self.view.pos + o)
  end
  return 0
end

function Stat.Start(builder)
  builder:StartObject(3)
end

function Stat.AddId(builder, id)
  builder:PrependUOffsetTRelativeSlot(0, id, 0)
end

function Stat.AddVal(builder, val)
  builder:PrependInt64Slot(1, val, 0)
end

function Stat.AddCount(builder, count)
  builder:PrependUint16Slot(2, count, 0)
end

function Stat.End(builder)
  return builder:EndObject()
end

return Stat


Test

--[[ MyGame.Example.Test

  Automatically generated by the FlatBuffers compiler, do not modify.
  Or modify. I'm a message, not a cop.

  flatc version: 23.5.9

  Declared by  : //monster_test.fbs
  Rooting type : MyGame.Example.Monster (//monster_test.fbs)

--]]

local flatbuffers = require('flatbuffers')

local Test = {}
local mt = {}

function Test.New()
  local o = {}
  setmetatable(o, {__index = mt})
  return o
end

function mt:Init(buf, pos)
  self.view = flatbuffers.view.New(buf, pos)
end

function mt:A()
  return self.view:Get(flatbuffers.N.Int16, self.view.pos + 0)
end

function mt:B()
  return self.view:Get(flatbuffers.N.Int8, self.view.pos + 2)
end

function Test.CreateTest(builder, a, b)
  builder:Prep(2, 4)
  builder:Pad(1)
  builder:PrependInt8(b)
  builder:PrependInt16(a)
  return builder:Offset()
end

return Test


TestSimpleTableWithEnum

--[[ MyGame.Example.TestSimpleTableWithEnum

  Automatically generated by the FlatBuffers compiler, do not modify.
  Or modify. I'm a message, not a cop.

  flatc version: 23.5.9

  Declared by  : //monster_test.fbs
  Rooting type : MyGame.Example.Monster (//monster_test.fbs)

--]]

local flatbuffers = require('flatbuffers')

local TestSimpleTableWithEnum = {}
local mt = {}

function TestSimpleTableWithEnum.New()
  local o = {}
  setmetatable(o, {__index = mt})
  return o
end

function mt:Init(buf, pos)
  self.view = flatbuffers.view.New(buf, pos)
end

function mt:Color()
  local o = self.view:Offset(4)
  if o ~= 0 then
    return self.view:Get(flatbuffers.N.Uint8, self.view.pos + o)
  end
  return 2
end

function TestSimpleTableWithEnum.Start(builder)
  builder:StartObject(1)
end

function TestSimpleTableWithEnum.AddColor(builder, color)
  builder:PrependUint8Slot(0, color, 2)
end

function TestSimpleTableWithEnum.End(builder)
  return builder:EndObject()
end

return TestSimpleTableWithEnum


LongEnum

--[[ MyGame.Example.LongEnum

  Automatically generated by the FlatBuffers compiler, do not modify.
  Or modify. I'm a message, not a cop.

  flatc version: 23.5.9

  Declared by  : //monster_test.fbs
  Rooting type : MyGame.Example.Monster (//monster_test.fbs)

--]]

local LongEnum = {
  LongOne = 2,
  LongTwo = 4,
  LongBig = 1099511627776,
}

return LongEnum


TypeAliases

--[[ MyGame.Example.TypeAliases

  Automatically generated by the FlatBuffers compiler, do not modify.
  Or modify. I'm a message, not a cop.

  flatc version: 23.5.9

  Declared by  : //monster_test.fbs
  Rooting type : MyGame.Example.Monster (//monster_test.fbs)

--]]

local flatbuffers = require('flatbuffers')

local TypeAliases = {}
local mt = {}

function TypeAliases.New()
  local o = {}
  setmetatable(o, {__index = mt})
  return o
end

function mt:Init(buf, pos)
  self.view = flatbuffers.view.New(buf, pos)
end

function mt:I8()
  local o = self.view:Offset(4)
  if o ~= 0 then
    return self.view:Get(flatbuffers.N.Int8, self.view.pos + o)
  end
  return 0
end

function mt:U8()
  local o = self.view:Offset(6)
  if o ~= 0 then
    return self.view:Get(flatbuffers.N.Uint8, self.view.pos + o)
  end
  return 0
end

function mt:I16()
  local o = self.view:Offset(8)
  if o ~= 0 then
    return self.view:Get(flatbuffers.N.Int16, self.view.pos + o)
  end
  return 0
end

function mt:U16()
  local o = self.view:Offset(10)
  if o ~= 0 then
    return self.view:Get(flatbuffers.N.Uint16, self.view.pos + o)
  end
  return 0
end

function mt:I32()
  local o = self.view:Offset(12)
  if o ~= 0 then
    return self.view:Get(flatbuffers.N.Int32, self.view.pos + o)
  end
  return 0
end

function mt:U32()
  local o = self.view:Offset(14)
  if o ~= 0 then
    return self.view:Get(flatbuffers.N.Uint32, self.view.pos + o)
  end
  return 0
end

function mt:I64()
  local o = self.view:Offset(16)
  if o ~= 0 then
    return self.view:Get(flatbuffers.N.Int64, self.view.pos + o)
  end
  return 0
end

function mt:U64()
  local o = self.view:Offset(18)
  if o ~= 0 then
    return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o)
  end
  return 0
end

function mt:F32()
  local o = self.view:Offset(20)
  if o ~= 0 then
    return self.view:Get(flatbuffers.N.Float32, self.view.pos + o)
  end
  return 0.0
end

function mt:F64()
  local o = self.view:Offset(22)
  if o ~= 0 then
    return self.view:Get(flatbuffers.N.Float64, self.view.pos + o)
  end
  return 0.0
end

function mt:V8(j)
  local o = self.view:Offset(24)
  if o ~= 0 then
    local a = self.view:Vector(o)
    return self.view:Get(flatbuffers.N.Int8, a + ((j-1) * 1))
  end
  return 0
end

function mt:V8AsString(start, stop)
  return self.view:VectorAsString(24, start, stop)
end

function mt:V8Length()
  local o = self.view:Offset(24)
  if o ~= 0 then
    return self.view:VectorLen(o)
  end
  return 0
end

function mt:Vf64(j)
  local o = self.view:Offset(26)
  if o ~= 0 then
    local a = self.view:Vector(o)
    return self.view:Get(flatbuffers.N.Float64, a + ((j-1) * 8))
  end
  return 0
end

function mt:Vf64Length()
  local o = self.view:Offset(26)
  if o ~= 0 then
    return self.view:VectorLen(o)
  end
  return 0
end

function TypeAliases.Start(builder)
  builder:StartObject(12)
end

function TypeAliases.AddI8(builder, i8)
  builder:PrependInt8Slot(0, i8, 0)
end

function TypeAliases.AddU8(builder, u8)
  builder:PrependUint8Slot(1, u8, 0)
end

function TypeAliases.AddI16(builder, i16)
  builder:PrependInt16Slot(2, i16, 0)
end

function TypeAliases.AddU16(builder, u16)
  builder:PrependUint16Slot(3, u16, 0)
end

function TypeAliases.AddI32(builder, i32)
  builder:PrependInt32Slot(4, i32, 0)
end

function TypeAliases.AddU32(builder, u32)
  builder:PrependUint32Slot(5, u32, 0)
end

function TypeAliases.AddI64(builder, i64)
  builder:PrependInt64Slot(6, i64, 0)
end

function TypeAliases.AddU64(builder, u64)
  builder:PrependUint64Slot(7, u64, 0)
end

function TypeAliases.AddF32(builder, f32)
  builder:PrependFloat32Slot(8, f32, 0.0)
end

function TypeAliases.AddF64(builder, f64)
  builder:PrependFloat64Slot(9, f64, 0.0)
end

function TypeAliases.AddV8(builder, v8)
  builder:PrependUOffsetTRelativeSlot(10, v8, 0)
end

function TypeAliases.StartV8Vector(builder, numElems)
  return builder:StartVector(1, numElems, 1)
end

function TypeAliases.AddVf64(builder, vf64)
  builder:PrependUOffsetTRelativeSlot(11, vf64, 0)
end

function TypeAliases.StartVf64Vector(builder, numElems)
  return builder:StartVector(8, numElems, 8)
end

function TypeAliases.End(builder)
  return builder:EndObject()
end

return TypeAliases


StructOfStructs

--[[ MyGame.Example.StructOfStructs

  Automatically generated by the FlatBuffers compiler, do not modify.
  Or modify. I'm a message, not a cop.

  flatc version: 23.5.9

  Declared by  : //monster_test.fbs
  Rooting type : MyGame.Example.Monster (//monster_test.fbs)

--]]

local flatbuffers = require('flatbuffers')

local StructOfStructs = {}
local mt = {}

function StructOfStructs.New()
  local o = {}
  setmetatable(o, {__index = mt})
  return o
end

function mt:Init(buf, pos)
  self.view = flatbuffers.view.New(buf, pos)
end

function mt:A(obj)
  obj:Init(self.view.bytes, self.view.pos + 0)
  return obj
end

function mt:B(obj)
  obj:Init(self.view.bytes, self.view.pos + 8)
  return obj
end

function mt:C(obj)
  obj:Init(self.view.bytes, self.view.pos + 12)
  return obj
end

function StructOfStructs.CreateStructOfStructs(builder, a_id, a_distance, b_a, b_b, c_id, c_distance)
  builder:Prep(4, 20)
  builder:Prep(4, 8)
  builder:PrependUint32(c_distance)
  builder:PrependUint32(c_id)
  builder:Prep(2, 4)
  builder:Pad(1)
  builder:PrependInt8(b_b)
  builder:PrependInt16(b_a)
  builder:Prep(4, 8)
  builder:PrependUint32(a_distance)
  builder:PrependUint32(a_id)
  return builder:Offset()
end

return StructOfStructs