modules

package
v0.0.0-...-a7a3610 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 1, 2019 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Cli = lua.TableMap{
	"add_command": func(eng *lua.Engine) int {
		cmdTbl := eng.PopTable()

		if !cmdTbl.IsTable() {
			eng.PushValue(eng.False())
			log("cli").Warn("{W}cli.add_command{x} was called without a table value")

			return 1
		}

		run := cmdTbl.Get("run")
		if !run.IsFunction() {
			eng.PushValue(eng.False())
			log("cli").Warn("No run command defined for the command.")

			return 1
		}

		cmd := new(cobra.Command)
		cmd.Use = cmdTbl.Get("name").AsString()
		if cmd.Use == "" {
			eng.PushValue(eng.False())
			log("cli").Warn("No name was provided for the command, a name is required.")

			return 1
		}

		cmd.Short = cmdTbl.Get("summary").AsString()
		cmd.Long = cmdTbl.Get("description").AsString()
		cmd.Run = func(cmd *cobra.Command, args []string) {
			luaArgs := eng.TableFromSlice(args)
			flags := make(map[string]interface{})
			cmd.Flags().VisitAll(func(f *pflag.Flag) {
				fval := reflect.ValueOf(f.Value)
				fval = reflect.Indirect(fval)
				fname := strings.ToLower(f.Name)
				flags[fname] = fval.Interface()
			})
			luaFlags := eng.TableFromMap(flags)
			_, err := run.Call(0, luaArgs, luaFlags)
			if err != nil {
				logger.NewWithSource(fmt.Sprintf("cmd(%s)", cmd.Use)).WithError(err).Fatal("Failed to execute lua command")
			}
		}

		cmdFlags := cmdTbl.Get("flags")
		if !cmdFlags.IsNil() {
			for i := 1; i <= cmdFlags.Len(); i++ {
				finfo := cmdFlags.RawGet(i)
				name := finfo.Get("name").AsString()
				short := finfo.Get("short").AsString()
				typ := finfo.Get("type").AsString()
				desc := finfo.Get("description").AsString()
				def := finfo.Get("default").AsRaw()

				if name == "" || short == "" || typ == "" || desc == "" {
					log("cli").WithFields(logger.Fields{
						"name":        name,
						"short":       short,
						"type":        typ,
						"description": desc,
					}).Warn("name, short, type and description are required for flags to be defined")

					continue
				}

				switch typ {
				case "string":
					s, _ := def.(string)
					cmd.Flags().StringP(name, short, s, desc)
				case "boolean":
					bval, _ := def.(bool)
					cmd.Flags().BoolP(name, short, bval, desc)
				case "number":
					f64, _ := def.(float64)
					cmd.Flags().Float64P(name, short, f64, desc)
				case "duration":
					d, _ := def.(string)
					dur, err := time.ParseDuration(d)
					if err != nil {
						eng.RaiseError(err.Error())

						return 0
					}
					cmd.Flags().DurationP(name, short, dur, desc)

				default:
					log("cli").WithField("type", typ).Warn("Type value is not valid.")
				}
			}
		}

		rootCmd := eng.Meta[keys.RootCmd].(*cobra.Command)
		rootCmd.AddCommand(cmd)

		eng.PushValue(eng.True())

		return 1
	},
}

Cli is a module designed specifically for adding new commands to the dragon application.

commandInfo: table = {
  name: string = name used to call the command
  summary: string? = short description of the subcommand
  description: string? = long description of the subcommand
  run: function = function to run if the command is called
  flags: table? {
    {
      type: string = "number" | "string" | "boolean"
      name: string = name of the flag, if it's "thing" the flag is "--thing"
      short: string = short description of the flag
      description: string = long description of the flag
      default: string | number | boolean | string(duration) = default value of the flag
    }
  }
}
add_command(cmd_info): boolean
  @param cmd_info: commandInfo = the information necessary to build out
    a new command for the command line interface.
  add a subcommand based on the information provided. Allowing any plguin
  to add their own commands.
View Source
var Config = lua.TableMap{
	"get": func(eng *lua.Engine) int {
		key := eng.PopString()
		iface := viper.Get(key)
		t := reflect.TypeOf(iface)
		switch t.Kind() {
		case reflect.Map:
			eng.PushValue(eng.TableFromMap(iface))
		case reflect.Slice:
			eng.PushValue(eng.TableFromSlice(iface))
		default:
			eng.PushValue(iface)
		}

		return 1
	},
}

Config provides a way for scripts to access data defined inside the Dragonfile.toml.

get(key): any
  @param key: string = the dot notation key to look up in the application
    configuration
  fetches a configuration value for the application by key
View Source
var Die = lua.TableMap{
	"d2":   random.D2,
	"d4":   random.D4,
	"d6":   random.D6,
	"d8":   random.D8,
	"d10":  random.D10,
	"d12":  random.D12,
	"d20":  random.D20,
	"d100": random.D100,
	"roll": func(e *lua.Engine) int {
		str := e.PopString()
		rolls := random.RollDie(str)
		e.PushValue(e.TableFromSlice(rolls))

		return 1
	},
}

Die is a module mapping that provides simulated die rolling methods to the the scripting engine.

d2(): number
  simulate rolling 1d2
d4(): number
  simulate rolling 1d4
d6(): number
  simulate rolling 1d6
d8(): number
  simulate rolling 1d8
d10(): number
  simulate rolling 1d10
d12(): number
  simulate rolling 1d12
d20(): number
  simulate rolling 1d20
d100(): number
  simulate rolling 1d100
roll(die): table
  @param die: string = the string defining how many of what to roll
  parse die input and roll the specified number of sided die, for example
  die.roll("3d8") will simulate rolling 3 8-sided die, and return the values
  as a table.
View Source
var Events = lua.TableMap{
	"Halt": events.ErrHalt,
	"emit": func(engine *lua.Engine) int {
		dataVal := engine.Nil()
		if engine.StackSize() >= 2 {
			dataVal = engine.PopValue()
		}
		evt := engine.PopValue().AsString()

		var data events.Data
		if dataVal.IsTable() {
			data = events.Data(dataVal.AsMapStringInterface())
		}

		go emitEvent(engine, evt, data)

		return 0
	},
	"emit_once": func(engine *lua.Engine) int {
		dataVal := engine.Nil()
		if engine.StackSize() >= 2 {
			dataVal = engine.PopValue()
		}
		evt := engine.PopValue().AsString()

		var data events.Data
		if dataVal.IsTable() {
			data = events.Data(dataVal.AsMapStringInterface())
		}

		go emitOnceEvent(engine, evt, data)

		return 0
	},
	"on": func(engine *lua.Engine) int {
		fn := engine.PopValue()
		evt := engine.PopValue().AsString()

		if evt != "" {
			bindEvent(engine, fn, evt)
		}

		return 0
	},
	"once": func(engine *lua.Engine) int {
		fn := engine.PopValue()
		evt := engine.PopValue().AsString()

		if evt != "" {
			bindOnceEvent(engine, fn, evt)
		}

		return 0
	},
}

Events is a module for emitting and receiving events in Lua.

Halt: (go error)
  used to halt event exuction, bypassing failure logs
emit(event[, data])
  @param event: string = the event string value to be emitted to
  @param data: table = a table of initial event properties to seed the
    event emission.
  emits the given event with the data, which can be nil or omitted
emit_once(event[, data])
  @param event: string = the event string value to be emitted to
  @param data: table = a table of initial event properties to seed the
    event emission.
  emits the event, similar to #emit, but any future binding to the given
  event will automatically be fired as this event has already been emitted,
  this is perfect for initializiation or one time load notices
on(event, handler)
  @param event: string = the event to associate the given handler to.
  @param handler: function = a function to execute if the event specified
    is emitted.
  registers the given function to handle the given event
once(event, handler: function)
  @param event: string = the event to associate the given handler to.
  @param handler: function = a function to execute if the event specified
    is emitted.
  registers the given function to handle the given event only one time
View Source
var Log = lua.TableMap{
	"error": func(eng *lua.Engine) int {
		performLog(eng, func(l logger.Log, msg string) {
			l.Error(msg)
		})

		return 0
	},
	"warn": func(eng *lua.Engine) int {
		performLog(eng, func(l logger.Log, msg string) {
			l.Warn(msg)
		})

		return 0
	},
	"info": func(eng *lua.Engine) int {
		performLog(eng, func(l logger.Log, msg string) {
			l.Info(msg)
		})

		return 0
	},
	"debug": func(eng *lua.Engine) int {
		performLog(eng, func(l logger.Log, msg string) {
			l.Debug(msg)
		})

		return 0
	},
}

Log is the definition of the Lua logging module.

error(msg[, data])
  @param msg: string = the message to log according the log configuraiton
    provided for the application
  @param data: table = associated data to log with the message, if any
    additional data is required.
  log message with data on the error level, data can be omitted or nil
warn(msg[, data])
  @param msg: string = the message to log according the log configuraiton
    provided for the application
  @param data: table = associated data to log with the message, if any
    additional data is required.
  log message with data on the warn level, data can be omitted or nil
info(msg[, data])
  @param msg: string = the message to log according the log configuraiton
    provided for the application
  @param data: table = associated data to log with the message, if any
    additional data is required.
  log message with data on the info level, data can be omitted or nil
debug(msg[, data])
  @param msg: string = the message to log according the log configuraiton
    provided for the application
  @param data: table = associated data to log with the message, if any
    additional data is required.
  log message with data on the debug level, data can be omitted or nil
View Source
var Password = lua.TableMap{

	"hash": func(engine *lua.Engine) int {
		passwordArg := engine.PopValue()
		if !passwordArg.IsString() {
			engine.PushValue(nil)

			return 1
		}
		password := passwordArg.AsString()

		cost := getBcryptCost()
		res, err := bcrypt.GenerateFromPassword([]byte(password), cost)
		if err != nil {
			engine.PushValue(nil)

			return 1
		}

		engine.PushValue(string(res))

		return 1
	},

	"is_valid": func(engine *lua.Engine) int {
		if engine.StackSize() < 2 {
			engine.PushValue(false)

			return 1
		}

		hashedArg := engine.PopValue()
		passwordArg := engine.PopValue()
		if !hashedArg.IsString() || !passwordArg.IsString() {
			engine.PushValue(false)

			return 1
		}

		hashed := hashedArg.AsString()
		password := passwordArg.AsString()

		err := bcrypt.CompareHashAndPassword([]byte(hashed), []byte(password))

		engine.PushValue(err == nil)

		return 1
	},
}

Password provides a method to take options to hash a password using the argon2i encryption algorithm.

hash(password): string
  @param password: string = a plaintext password value
  hashes the plain text password using the bcrypt algorithm for hasing
  passwords and the configured cost in Dragonfile.toml.
isValid(password: string, hash: string): string
  @param password string = the plain text password entered by the user that
    will be compared against the hash
  @param hash: string = a hash of an encrypted password that the new
    password should match after encryption
  hashes the given password and compares it to the hashed password (using
  the same cost that the hashed password was generated with) and compares
  the result.
View Source
var Random = lua.TableMap{
	"gen":   random.Intn,
	"range": random.Range,
}

Random provides a means for generating random numbers up to a maximum value or between a minimum and a maximum.

gen(max): number
  @param max: number = the maximum value to generated a number to
  generate a number from 0 up to the max value given.
range(min: number, max: number): number
  @param min: number = the lower bound (inclusive) of generated random
    numbers
  @param max: number = the upper bound (exclusive) of generated random
    numbers
  generate a number between the given minimum and maximum, the range
  [min, max)
View Source
var Sutil = lua.TableMap{
	"split": func(eng *lua.Engine) int {
		sep := eng.PopString()
		str := eng.PopString()

		strs := strings.Split(str, sep)
		list := eng.NewTable()
		for _, str := range strs {
			list.Append(str)
		}

		eng.PushValue(list)

		return 1
	},
	"join": func(eng *lua.Engine) int {
		joiner := eng.PopString()
		words := eng.PopTable()

		var strs []string
		words.ForEach(func(_ *lua.Value, value *lua.Value) {
			strs = append(strs, value.AsString())
		})

		eng.PushValue(strings.Join(strs, joiner))

		return 1
	},
	"test_rx": func(eng *lua.Engine) int {
		haystack := eng.PopString()
		needle := eng.PopString()

		rx, err := fetchRx(needle)
		if err != nil {
			eng.PushValue(eng.False())

			return 1
		}

		res := rx.MatchString(haystack)
		eng.PushValue(res)

		return 1
	},
	"starts_with": func(eng *lua.Engine) int {
		prefix := eng.PopString()
		str := eng.PopString()

		eng.PushValue(strings.HasPrefix(str, prefix))

		return 1
	},
	"ends_with": func(eng *lua.Engine) int {
		suffix := eng.PopString()
		str := eng.PopString()

		eng.PushValue(strings.HasSuffix(str, suffix))

		return 1
	},
	"contains": func(eng *lua.Engine) int {
		needle := eng.PopString()
		haystack := eng.PopString()

		eng.PushValue(strings.Contains(haystack, needle))

		return 1
	},
	"matches": func(eng *lua.Engine) int {
		haystack := eng.PopString()
		needle := eng.PopString()

		rx, err := fetchRx(needle)
		if err != nil {
			eng.PushValue(eng.NewTable())

			return 1
		}

		res := rx.FindAllString(haystack, -1)

		eng.PushValue(eng.TableFromSlice(res))

		return 1
	},
	"inspect_value": func(eng *lua.Engine) int {
		val := eng.PopValue()
		eng.PushValue(val.Inspect(""))

		return 1
	},
}

Sutil contains several features that Lua string handling lacks, things like joining and regex matching and splitting and trimming and various other things.

split(input, separator): table
  @param input: string = the string to perform the split operation on
  @param separator: string = the separator with which to split the string
    by
  split the input string in parts based on matching the separator string
join(words, joiner): string
  @param words: table = list of values that should be joined together
  @param joiner: string = a string value that should act as the glue
    between all values in (words) from ealier.
  combine the input list of strings with the joiner
test_rx(needle, haystack): boolean
  @param needle: pattern = A Go regular expressoin pattern used to test
    against the given string value?
  @param haystack: string = the body to perform the search within
  test the haystack against the needle (regular expression search)
starts_with(str, prefix): boolean
  @param str: string = the value to test against the prefix
  @param prefix: string = the prefix that is in question
  determines if the string starts with the given substring
ends_with(str, suffix): boolean
  @param str: string = the value to test against the suffix
  @param suffix: string = the suffix that is in question
  determines if the string ends with the given substring
contains(haystack, needle): boolean
  @param haystack: string = the body of data to be searched by the pattern.
  @param needle: string = the pattern (regular expression) to search for
    within the text.
  determines if substring is present in the given string
matches(needle, haystack): table
  @param needle: string = the pattern (regular expression) to compare
    against the haystack
  @param haystack: string = the body of data to be compared against the
    pattern
  a list of strings that match the needle (regexp)
View Source
var Talon = lua.TableMap{
	"exec": func(engine *lua.Engine) int {
		query, err := getTalonQuery(engine)
		if err != nil {
			engine.RaiseError(err.Error())

			return 0
		}

		result, err := query.Exec()
		if err != nil {
			engine.RaiseError(err.Error())

			return 0
		}

		engine.PushValue(result)

		return 1
	},
	"query": func(engine *lua.Engine) int {
		query, err := getTalonQuery(engine)
		if err != nil {
			engine.RaiseError(err.Error())

			return 0
		}

		rows, err := query.Query()
		if err != nil {
			engine.RaiseError(err.Error())

			return 0
		}

		engine.PushValue(talonToLua(engine, rows))

		return 1
	},
}

Talon is the core database Lua wrapper, giving the coder access to running queries against the database

exec(cypher, properties): talon.Result
  @param cypher: string - the cypher query to execute on the database
    server
  @param properties: table - properties to fill the cypher query with
    before execution
  @errors raises an error if there is an issue with the database connection
    or the query construction
  executes a query on the database and returns a result value, this should
  be used with queries that don't return a result set (like creating,
  editing and deleting).
query(cypher, properties): talon.Rows
  @param cypher: string - the cypher query to execute on the database
    server
  @param properties: table - properties to fill the cypher query with
    before execution
  @errors raises an error if there is an issue with the database connection
    or the query construction
  executes a query on the database server and returns a set of rows with
  the queries results.
talon.Rows
  next(): talon.Row
    the rowset is a lazy loaded series of rows, next will return the next
    row in the set of rows returned by the query. If there are no more
    rows this will return nil.
  close()
    close the set of rows, this is a _very_ good thing to do to clean up
    after your queries. It is undefined behavior to fail to close your
    row sets.
  inspect(): string
    return a debug view into the talon.Rows value.
talon.Row
  get(key): any
    @param key: string | number - the field name in the row or the field
      index in the result.
    this will return any value associated with the index or field name or
    nil if no value is found.
talon.Node
  @property id: number - numeric auto id number assigned to the node by
    the database
  @property labels: table - a list of labels associated with the node; not
    quite a table, it's a Go slice but functions similarly
  @property properties: table - a key/vale paring of properties associated
    with the node; not quite a table, a Go map but functions like a table.
  get(key): any
    @param key: string - the name of the property to fetch from the node,
      mostly a shorthand for accessing properties
    fetch a property by key from the node.
talon.Relationship
  @property id: number - numeric auto id number assigned to the node by
    the database
  @property start_node_id: number - the auto identifier of the node that
    this relationship originates from
  @property end_node_id: number - the auto identifier of the node that
    this relationship executes at
  @property name: string - the label of the label (or name)
  @property properties: table - a key/vale paring of properties associated
    with the node; not quite a table, a Go map but functions like a table.
  @property bounded: boolean - denotes whether start_node_id and
    end_node_id will be set. If a relationship is bounded then it's start
    and end points are recorded, if it's not bounded they will not be set
    (most likely returning 0).
  get(key): any
    @param key: string - the name of the property to fetch from the
      relationship, mostly a shorthand for accessing properties
    fetch a property by key from the relationship.
talon.Path
  functionally a table (list) of alternating node/relationship values from
  one node to another.
View Source
var Time = lua.TableMap{

	"now": func() *instantValue {
		t := instantValue(time.Now().UTC())

		return &t
	},

	"parse": func(fmt, date string) *instantValue {
		t, err := time.Parse(fmt, date)
		if err != nil {
			return nil
		}
		iv := instantValue(t)

		return &iv
	},

	"create": func(engine *lua.Engine) int {
		if engine.StackSize() < 1 {
			engine.RaiseError("a map of date information is required")

			return 0
		}

		arg := engine.PopValue()
		m := arg.AsMapStringInterface()

		iv, err := instantFromMap(m)
		if err != nil {
			engine.RaiseError(err.Error())

			return 0
		}

		engine.PushValue(iv)

		return 1
	},

	"unix": func(ts int64) *instantValue {
		t := time.Unix(ts, 0).UTC()
		iv := instantValue(t)

		return &iv
	},

	"duration": func(eng *lua.Engine) int {
		if eng.StackSize() == 0 {
			eng.ArgumentError(1, "expected an argument, but received none")

			return 0
		}

		val := eng.PopValue()
		var dur float64
		switch {
		case val.IsNumber():
			dur = val.AsNumber()
		case val.IsTable():
			dur = durationFromMap(val.AsMapStringInterface())
		case val.IsString():
			dur = durationFromString(val.AsString())
		}

		eng.PushValue(float64(floatToDuration(dur)))

		return 1
	},

	"duration_parts": func(f float64) map[string]float64 {
		if f > math.MaxInt64 || f < math.MinInt64 {
			return map[string]float64{
				"out_of_range": f,
			}
		}

		dur := floatToDuration(f)
		durMap := make(map[string]float64)

		year := durationMap["year"]
		temp := dur / year
		dur %= year
		durMap["years"] = float64(temp)

		month := durationMap["month"]
		temp = dur / month
		dur %= month
		durMap["months"] = float64(temp)

		week := durationMap["week"]
		temp = dur / week
		dur %= week
		durMap["weeks"] = float64(temp)

		day := durationMap["day"]
		temp = dur / day
		dur %= day
		durMap["days"] = float64(temp)

		temp = dur / time.Hour
		dur %= time.Hour
		durMap["hours"] = float64(temp)

		temp = dur / time.Minute
		dur %= time.Minute
		durMap["minutes"] = float64(temp)

		temp = dur / time.Second
		dur %= time.Second
		durMap["seconds"] = float64(temp)

		temp = dur / time.Millisecond
		dur %= time.Millisecond
		durMap["milliseconds"] = float64(temp)

		durMap["nanoseconds"] = float64(dur)

		return durMap
	},
}

Time provides some basic time functions for creating a time in Lua.

instantData: table = {
  year: number = the year the instant is set in; default: current year,
  month: string | number = the three letter name, full name or numeric
    represenation of the month: "jan", "January", 1; default: January
  day: number = the day in which the instant is to be set; default: 1,
  hour: number = the hour (0-23) of the instant; default: 0,
  min: number = the minute (0-59) of the instant; default: 0,
  minute: number = alias for min
  sec: number = the second (0-59) of the instant; default: 0,
  second: number = alias for sec
  milli: number = the number of milliseconds (past the second) of the
    instant; defualt 0
  millisecond: number = alias for milli
  nano: number = the number of nanoseconds (past the second) of the
    instant; default: 0,
  nanosecond: number = alias for nano
  zone: string = the name of the time zone for the instant in anything
    other than "UTC"; default: UTC
}
durationData: table = {
  nanosecond: number = number of nanoseconds in this duration,
  millisecond: number = number of milliseconds in this duration,
  second: number = number of seconds in this duration,
  minute: number = number of minutes in this duration,
  hour: number = number of hours in this duration,
  day: number = number of days in this duration (assumed 24 hours),
  week: number = number of weeks in this duration (assumed 7 days),
  month: number = number of months in this duration (assumed 30 days),
  year: number = number of years in this duration (assumed 365 days)
}
now(): time.Instant
  returns an instant value representing the current time in the UTC time
  time zone.
parse(format, date): time.Instant | nil
  @param format: string = the format to be used to parse the given date
    date string with. This format is based on the same format that Go's
    time package uses, 'Mon Jan 2 15:04:05 -0700 MST 2006', you can use a
    wide variety of this date to specify the format.
  @param date: string = the stringified date value that is to be parsed
    with the given format.
  attempts to parse the date value with the given format and returns an
  instant value based on the given date string value -- if the date fails
  to parse then nil will be returned.
create(data): time.Instant
  @param data: instantData = a table containing the values to construct the
    instant value from. All keys are optional.
  builds an instant with any given information using default fallbacks
  and returns this new instant.
unix(timestamp): time.Instant
  @param timestamp: number = a Unix timestamp value used to generate an
    instant value for the given date based on the rules of unix timestamps.
  this method generates a time.Instant value based on the give timestamp.
duration(generator): number
  @param generator: table(durationData) | number | string = either a table
    defining the values in the duration, a string encoding of the duration
    or a numeric value that is the duration.
  this method generates a duration value, it's range is roughly -290..290
  years. forcing beyond this boundary is undefined and should be avoided at
  all costs.
duration_parts(duration): table
  @param duration: number = the number of nanoseconds representing a period
    an arbitrary passing of time with no start point
  take a duration value and break it into a map containing the named
  components, like a duration of "1w" would come back with {weeks = 1}.
  given the nature of durations being numbers, if a generated duration has
  overlapping periods you can expect to get different components back, for
  example "8d" (8 days) = {weeks = 1, days = 1}
time.Instant
  format(format): string
    @param format: string = the format that will be used to produce a
      string representation
    formats the date according to the string value. Like time.parse this
    method uses the Go base date 'Mon Jan 2 15:04:05 -0700 MST 2006' as a
    means for defining the format
  unix(): number
    returns the unix timestamp value for the given instant in time.
  in_zone(zone): time.Instant
    @param zone: string = the name of the time zone to transition this
      instant to.
    this will create a new instant and return that value in the given time
    zome.
  zone(): string
    return the name of the time zone (not 100% accurate) used for the
    instant's current time zone. It's not super accurate becuase if you
    use 'local' you get 'local' back.
  add(duration): time.Instant
    @param duration: number = the number of nanonseconds that need to be
      to the current instant.
    add a fixed duration to the given date and return the results as a new
    date value.
  sub(duration): time.Instant
    @param duration: number = the number of nanonseconds that need to be
      to the current instant.
    much the same as :add, however this method will negate the duration.
  sub_date(oinstant): number
    @param oinstant: time.Instant = the instant you wish to subtract from the
      current instant.
    returns the duration, or nanosecond difference, between the original
    instant and the instant you're subtracting from.
  is_before(oinstant): boolean
    @param oinstant: time.Instant = the other instant you're comparing
      this instant too.
    returns true if the current instant occurred _before_ the other
    instant.
  is_after(oinstant): boolean
    @param oinstant: time.Instant = the other instant you're comparing
      this instant too.
    the opposite of :is_before, this checks to see if this instant occurred
    _after_ the other.
  inspect(): string
    returns a string that represents a debug output, primarily for use in
    the REPL.
View Source
var Tmpl = lua.TableMap{
	"register": func(name, contents string) bool {
		err := tmpl.Register(name, contents)

		if err != nil {
			fields := logger.Fields{
				"error": err.Error(),
			}
			if len(contents) < 255 {
				fields["template"] = contents
			}
			log("tmpl").WithFields(fields).Error("Register failed from script with error")
		}

		return err == nil
	},
	"render": func(engine *lua.Engine) int {
		data := engine.PopTable().AsMapStringInterface()
		name := engine.PopString()

		log := log("tmpl").WithField("tmpl_name", name)

		t, err := tmpl.Template(name)
		if err != nil {
			log.WithError(err).Error("Failed to fetch template name.")
			engine.RaiseError(err.Error())

			return 0
		}
		result, err := t.Render(data)
		if err != nil {
			log.WithFields(logger.Fields{
				"error": err.Error(),
				"data":  data,
			}).Error("Failed to render template from requested in script.")
		}

		engine.PushValue(result)

		return 1
	},
	"render_in_layout": func(eng *lua.Engine) int {
		ldata := eng.PopValue()
		children := eng.PopValue()
		parent := eng.PopString()

		pt, err := tmpl.Template(parent)
		if err != nil {
			log("tmpl").WithError(err).WithField("template", parent).Warn("Parent template requested but undefined, returning empty string.")
			eng.PushValue("")

			return 1
		}

		var data map[string]interface{}
		if ldata.IsTable() {
			data = ldata.AsMapStringInterface()
		} else {
			data = make(map[string]interface{})
		}

		switch {
		case children.IsString():
			cs := children.AsString()
			r, err := tmpl.Template(cs)

			if err != nil {
				log("tmpl").WithError(err).WithField("tempalte", cs).Warn("Template requested, but doesn't exit. Using empty string.")
				data["content"] = ""
			} else {
				data["content"], err = r.Render(data)
				if err != nil {
					log("tmpl").WithError(err).WithField("template", cs).Error("Failed to render template")
					data["content"] = ""
				}
			}
		case children.IsTable():
			children.ForEach(func(key, val *lua.Value) {
				if key.IsString() {
					ks := key.AsString()
					if val.IsString() {
						vs := val.AsString()
						r, err := tmpl.Template(vs)
						if err != nil {
							log("tmpl").WithError(err).WithField("tempalte", vs).Warn("Template requested, but doesn't exit. Using empty string.")
							data[ks] = ""

							return
						}
						data[ks], err = r.Render(data)
						if err != nil {
							log("tmpl").WithError(err).WithField("template", ks).Error("Failed to render template.")
							data[ks] = ""
						}
					} else {
						log("tmpl").WithFields(logger.Fields{
							"template": ks,
							"type":     val.String(),
						}).Warn("Non-string value given as name of template, using empty string.")
						data[ks] = ""
					}
				} else {
					log("tmpl").WithField("type", key.String()).Warn("Non-string key provided as key of rendered template, ignoring")
				}
			})
		}

		res, err := pt.Render(data)
		if err != nil {
			log("tmpl").WithError(err).WithField("template", pt).Error("Failed to render parent template, returning empty string.")
			eng.PushValue("")

			return 1
		}

		eng.PushValue(res)

		return 1
	},
}

Tmpl is the templating module accessible in scripts. This module consists of two accessible methods:

register(name, body)
  @param name: string = the name to associate with this template after
  @param body: string = the uncompiled body of the template
    registration
  register a template with the given name
render(name, data)
  @param name: string = the name of the compiled template to use for
    generating output
  @param data: table = a table of data to provide to the rendering of the
    named templates
  render the template with the given name using the given data to populate
  it
render_in_layout(layout, children, data)
  @param layout: string = the name of the layout template to render.
  @param children: string or table = the children to render in the layout.
    if provided as a string, then the name to use in the layout is
    'content', otherise this is table of field names -> template names to
    use in generating layout content.
  @param data: table = a table of data to provide to the rendering of the
    named templates (used for all views, so must be merged)
  render the child templates with the provided and building an additional
  set of data containing the rendered children before rendering the final
  layout template which can position the child templates via normal
  rendering means.
View Source
var UUID = lua.TableMap{
	"new": func() string {
		u := uuid.NewV1()

		return u.String()
	},
}

UUID enables the generation of UUID v1 values, as necessary.

new(): string
  a new v1 UUID value in string format.

Functions

func ScriptLoader

func ScriptLoader(scriptName string) func(*lua.Engine)

func TalonLoader

func TalonLoader(engine *lua.Engine)

TalonLoader will create the meta tables for talon.Row and talon.Rows for this Engine.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL